jquery 的ajax请求传递json数据给struts的action

来源:互联网 发布:互联网数据分析招聘 编辑:程序博客网 时间:2024/06/05 18:57

1.ajax用法

<span style="white-space:pre"></span>$.ajax({ dataType:'json',//标示使用json数据格式 url:'AddNotice!AddNotice.action',//url,记得带action data:{<span style="color:#ff0000;">title</span>:<span style="color:#33ff33;">title</span>,content:content,notice:notice},//                       //红色的和action中的变量相同,绿色的是js变量<span style="white-space:pre"></span>     type:'post',//post请求 success:function(data,status){ $.messager.show(data.msg);//在这个函数中可以接受action传回的数据,并作处理,例如data.msg这个msg就是action中传回的json的键名,data.msg获得值,$.messager.show()是easyui中的函数,使用的话是需要加相应的js引用,请看我的另一篇介绍<span style="white-space:pre"></span>},<span style="white-space:pre"></span>error:function(data,status) { $.messager.show("系统提示","操作失败","warning");<span style="white-space:pre"></span> } });

2.后台action用法
首先添加相应的.jar,这里付一下struts的相应jar下载链接,包括json,如果不知道导入哪个jar,就全都倒进去。

百度云
  

   2.1然后在struts.xml中的package中继承json-default,一定要的

 <package name="resource" namespace="/"  extends="json-default">
否则action解析不了。
然后传回数据的时候这样。

JSONObject jsonObject = JSONUtil.NewJSonObject();msg = "改公告已经保存";jsonObject.put("msg", msg);try {JSONUtil.ResponsePrint(jsonObject);} catch (IOException e) {e.printStackTrace();}
这个msg就是前台data.msg中的msg,
JSONUtil是自己写的工具类
public static JSONObject NewJSonObject(){return new JSONObject();}public static void ResponsePrint(Object jsonObject) throws IOException {HttpServletResponse response = ServletActionContext.getResponse();response.setContentType("text/html; charset=utf-8");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache, must-revalidate");PrintWriter pWriter = response.getWriter();pWriter.print(jsonObject);pWriter.flush();pWriter.close();}
完成!

0 1
原创粉丝点击