1. 程式人生 > >ajax前臺與struts2中action交互詳見

ajax前臺與struts2中action交互詳見

gin def print ces 返回 collect jdk char int

第一種方法

  利用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裏所有屬性!

  

ajax前臺與struts2中action交互詳見