SpringMVC+JSP中关于JQuery ajax提交的Content-Type参数设置application/json和application/x-www-form-urlencoded区别
页面是用的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字符串。
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/01/differences-in-content-type-parameter-settings-for-jquery-ajax-request-in-springmvc-jsp-between-application-json-and-application-x-www-form-urlencoded/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论