最近涉及到需要用AJAX(基于JQUERY)发送请求传递数组参数,如下:假设j是个数组
$.ajax({
type : "POST",
url : '../../../system/downloadFile',
traditional: true,//取消深度序列化
data: {
name:j
},
dataType: "json",
success : function(data) {
if(data.isSuccess == "true" || data.isSuccess == true) {
} else{
}
}
});
Controller里打断点name为NULL值,如下:
@RequestMapping({ "downloadFile" })
public @ResponseBody Object downloadFile(HttpServletRequest request,@RequestParam(value = "name", required=false) String name) {
return null;// CommonUtils.convertBeanToJson(sibList);
}
上网查资料得知AJAX对数组参数有一个序列化的过程,导致后台服务获取,后来总结可以通过两种方法实现:
1.JS中AJAX请求处加入raditional: true,告诉AJAX不要深度序列化,后台返回一个类似于拼接后的字符串,并且需要split(当然还有别的方式),但是这种方法有个BUG,截取时候容易定位混淆。
2.将数组JSON化
function arrayToJson(o) {
var r = [];
if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
if (typeof o == "object") {
if (!o.sort) {
for (var i in o)
r.push(i + ":" + arrayToJson(o[i]));
if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
r.push("toString:" + o.toString.toString());
}
r = "{" + r.join() + "}";
} else {
for (var i = 0; i < o.length; i++) {
r.push(arrayToJson(o[i]));
}
r = "[" + r.join() + "]";
}
return r;
}
return o.toString();
}
后台返回字符串,个人认为这种方法比较靠谱。