javascript方法: JSON.stringify(jsonObj), 将JSON对象转为字符串
项目中需要将复杂的对象从前端传到后端, 通过struts2的拦截器, 直接转换注入到action的属性中
比如 private List<Bean> test;
当然可以将data写成:
{ "test[0].note":"note a", "test[0].username":"username a",
"test[1].note":"note b", "test[1].username":"username b"
}
直接将obj做为data传给$.ajax不行, struts2没配置json拦截器也不行
javascript:
var jsonObj = {
"test":
[{"note":"note a", "username":"username a"},
{"note":"note b", "username":"username b"}
]
};
var str = JSON.stringify(jsonObj);
//console.log("result: "+str);
$.ajax({
url: "input.action",
contentType: 'application/json',
data: str,
type: "post",
datatype: "json",
success: function(data){
console.log(data);
}
});
bean:
public class Bean{
private String note;
private String username;
//getter and setter
}
action:
public class TestAction extends BaseAction{
private List<Bean> test;
public List<Bean> getTest() {
return test;
}
public void setTest(List<Bean> test) {
this.test = test;
}
public String input(){
System.out.println(test);
for(Bean bean: test){
System.out.println(bean.getNote());
}
return SUCCESS;
}
}
struts2:
<package name="test" namespace="/test" extends="json-default">
<interceptors>
<interceptor-stack name="def">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="json"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="def"></default-interceptor-ref>
<action name="input" class="testAction" method="input">
<result type="json"></result>
</action>
</package>
spring配置省略

本文详细介绍了如何使用JavaScript的JSON.stringify方法将复杂的对象转换为JSON字符串,并通过Struts2的JSON拦截器将其传递给Action。通过实例演示了如何将对象数组作为参数传递,以及如何在Struts2 Action中接收并处理这些数据。
6912

被折叠的 条评论
为什么被折叠?



