将serialize数组传递给struts2动作
我计划将整个表单数据以JSON格式发布到Struts2 Action。 以下是我的代码片段。 纠正我出错的地方或帮助我,以便我可以正确地获取Action文件中的所有值。 我在Action文件中的所有SOP都显示为null
var MyForm = $("#companyform").serializeArray(); var data = JSON.stringify(MyForm); $.ajax({ type: 'POST', url:'createcompany.action?jsonRequestdata='+data, dataType: 'json', success: function(data){ console.log(stringify(data)); }});
我的表单数据变为[{"name":"tan","value":"rrr"},{"name":"pan","value":"adf"},{"name":"tod","value":"1"}]
Struts2动作文件:
String jsonRequestdata; public String execute() throws Exception { JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata); JSONObject json = (JSONObject) jsonArr.get(0); System.out.println("TAN=" + json.get("tan")); System.out.println("PAN=" + json.get("pan")); System.out.println("TOD=" + json.get("tod")); return "success"; }
目前的输出
TAN=null PAN=null TOD=null
要使用POST请求发送数据,您应该使用这样的data
属性
$.ajax({ type: 'POST', url:'createcompany.action' data: 'jsonRequestdata='+data dataType: 'json', success: function(data){ console.log(JSON.stringify(data.jsonRequestdata)); } });
要获取操作bean中的数据,您需要使用公共setter
public void setJsonRequestdata(String data){ this.jsonRequestdata = data; }
要将数据返回到success
回调函数,请使用public getter
public String getJsonRequestdata(){ return this.jsonRequestdata; }
要从操作返回JSON,请使用结果类型json
。
jsonRequestdata
注意,如果将json
拦截器添加到操作配置中,则可以在请求中使用JSON数据。 使用Content-Type: "application/json"
带有请求的Content-Type: "application/json"
将触发Struts2解析请求并自动将其反序列化为action bean。
由于我使用的是名称,因此我必须使用名称来获取它。 以下是工作代码
JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata); for(int i=0;i