在用 spring mvc 写应用的时候发现jquery传递的【json数组对象】参数后台接收不到,多订单的处理,ajax请求:
var cmd = {orders:[{"storeId":"0a1", "address":"西斗门路2号", "goods":[{"goodsId":""}, {"goodsId":""}, {"goodsId":""}]},{"storeId":"0a1", "address":"西斗门路2号", "goods":[{"goodsId":""}, {"goodsId":""}, {"goodsId":""}]}]} $.ajax({
url : url,
type : "POST",
datatype:"json",
data : cmd,
success : function(data, stats) {
if (stats == "success") {
// window.location.href="/yc"
}
},
error : function(data) {
alert("请求失败");
}
});
开始如何传后台用 @RequestParam 去接收如何都接不到,分析下请求头,原来是json格式没转换
Origin:http://localhost
Referer:http://localhost/test/myorder
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
orders[][storeId]:0a1
orders[][address]:西斗门路2号
orders[][goods][][goodsId]:
orders[][goods][][goodsId]:
orders[][goods][][goodsId]:
orders[][storeId]:0a1
orders[][address]:西斗门路2号
orders[][goods][][goodsId]:
orders[][goods][][goodsId]:
orders[][goods][][goodsId]:
Response Headersview source
Content-Length:
Content-Type:text/html;charset=utf-
Date:Mon, Nov :: GMT
Server:Apache-Coyote/1.1
通过观察,orders[0][storeId]:0a1
orders[0][address]:西斗门路2号
orders[0][goods][0][goodsId]:1 变成了多维数组的格式传递,没有按json对象的方式传递(原以为 jquery会自动转的,可惜我想多了,所以出现了乌龙)。
下了个jquery的json插件,jquery.json-2.4.js 转了下json;但是问题又来了,传的格式正确但是后台还是接不到,打印了下request.getParameterMap(),参数按json格式传进来,但是接的方式又出现了问题,用string接肯定不行,String数组接也接不到,List也接不到,网上查查相关Controller的接收json对象的方式,需要用@RequestBody来进行接收,为了方便干脆把 orders去掉 直接用json数组
var cmd = [{"storeId":"0a1", "address":"西斗门路2号", "goods":[{"goodsId":""}, {"goodsId":""}, {"goodsId":""}]},{"storeId":"0a1", "address":"西斗门路2号", "goods":[{"goodsId":""}, {"goodsId":""}, {"goodsId":""}]}]
后台用
(@RequestBody List orders)
检查下参数写法,应该没错,测试之后还是有问题 报了这样一个错误:
POST http://localhost/test/order 415 (Unsupported Media Type) 这个问题应该是前台请求过程中没有指明contentType,ajax中加上contentType: "application/json; charset=utf-8",再测试,果然可以了。完整代码如下:
ajax:
var cmd = [{"storeId":"0a1", "address":"西斗门路2号", "goods":[{"goodsId":""}, {"goodsId":""}, {"goodsId":""}]},{"storeId":"0a1", "address":"西斗门路2号", "goods":[{"goodsId":""}, {"goodsId":""}, {"goodsId":""}]}] $.ajax({
url : url,
type : "POST",
datatype:"json",
contentType: "application/json; charset=utf-8",
data : $toJSON(cmd),
success : function(data, stats) {
if (stats == "success") {
// window.location.href="/yc"
}
},
error : function(data) {
alert("请求失败");
}
});
Controller method:
@RequestMapping(value = "/order", method = RequestMethod.POST)
public ModelAndView order(@RequestBody List<Map<String,Object>> orders) {
System.out.println("orders size:" + orders.size());
}
以上希望能为遇到类似问题的朋友提供一些帮助。