页面是用的JSP,后台用的Spring MVC
使用JQuery的ajax需要设置Content-Type,Content-Type的设置有以下几种常用的
"Content-Type": "application/x-www-form-urlencoded" //适用于大部分情况
"Content-Type": "application/json" //适用于复杂JSON数据的提交
"Content-Type": "multipart/form-data" //适用于文件上传
application/x-www-form-urlencoded
application/x-www-form-urlencoded是JQuery ajax默认的提交方式,当不写contentType时即是此种方式,代表使用表单形式提交。
JSP:
$.ajax({
type: "POST",
url: "${basePath}/comment",
contentType: "application/x-www-form-urlencoded",
dataType: "json", //表示返回值类型,不必须
data: {comment: 'appblog.cn'},
success: function (result) {
alert(result);
}
});
后台:
@RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST)
@ResponseBody
public Result reviewOrder(@PathVariable("orderId") Long orderId, HttpServletRequest request) {
String comment = request.getParameter("comment");
}
application/json
使用application/x-www-form-urlencoded只能提交简单类型的json数据,当json数据很复杂时就须要使用application/json
JSP:
$.ajax({
type: "POST",
url: "${basePath}/comment",
contentType: "application/json", //必须有
dataType: "json", //表示返回值类型,不必须
data: JSON.stringify({'comment': 'appblog.cn'}),
success: function (result) {
alert(result);
}
});
后台
@RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST)
@ResponseBody
public Result reviewOrder(@PathVariable("orderId") Long orderId, @RequestBody Review review, HttpServletRequest request) {
String comment1 = request.getParameter("ids"); //输出null
String comment2 = review.getComment();
}
public class Review {
String comment;
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
也可以使用JSONObject
@RequestMapping(value = "/order/{orderId}", method = RequestMethod.POST)
@ResponseBody
public Result reviewOrder(@PathVariable("orderId") Long orderId, @RequestBody JSONObject object, HttpServletRequest request) {
String comment = object.getString("comment");
}
总结:当使用application/x-www-form-urlencoded时其实JSP会默认把json数据认为是一个对象,而使用application/json时需要向后台传入一个JSON字符串,所以要用JSON.stringify函数把JSON对象转成json字符串。