第一種方法:
利用Servlet API,用response的.getWriter()方法獲得PrintWriter
Action代碼:
public Object ajax(){ HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("交互數據"); return NONE; }
ajax代碼(跟以前的一樣):
$.ajax({ type:"post", url:"/Test/ajax.action", data:{}, dataType:"json", success:function(data){ alert(data) }, error:function(data){ alert("錯誤"); } });
第二種方法:利用struts2 json插件
1.所需架包
commons-lang.jar;
json-lib-2.3-jdk15.jar;
struts2-json-plugin-2.2.3.jar;
ezmorph-1.0.1.jar;
commons-beanutils-1.9.2.jar;
commons-collections-3.1.jar(commons-collections-2可能會報錯)
2.struts.xml配置文件
在package中extends應該改為json-default而不是struts-default,result的type設為json
<package name="default" namespace="/" extends="json-default"></package>
<action ...省略>
<result name="success" type="json"></result>
</action>
3.action代碼:
直接對需要的屬性賦值,然后return "success";
4.ajax代碼:
跟之前調用一樣,注意成功之后返回的數據是action里所有屬性!