springmvc+jsp中關於JQuery ajax提交的Content-Type引數設定application/json和application/x-www-form-urlencoded區別
阿新 • • 發佈:2018-12-13
介紹
本人頁面是用的JSP,後臺用的Spring MVC。
使用JQ的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是jq ajax預設的提交方式,當不寫contentType時即是此種方式,代表使用表單形式提交。
JSP:
$.ajax({
type: "POST",
url: "${webRoot}/ggzy/ggzyZhzfkController.do?flfgNameQuery",
contentType: "application/x-www-form-urlencoded",
dataType: "json", //表示返回值型別,不必須
data: {ids: '1'},
success: function (jsonResult) {
alert(jsonResult);
}
});
後臺:
public AjaxJson flfgNameQuery (String ids,HttpServletRequest req) {
String ids1 = req.getParameter("ids");
System.out.println(ids); //輸出1
System.out.println(ids1); //輸出1
}
application/json
使用application/x-www-form-urlencoded只能提交簡單型別的json資料,當json資料很複雜時就須要使用application/json。
JSP:
$.ajax({
type: "POST" ,
url: "${webRoot}/ggzy/ggzyZhzfkController.do?flfgNameQuery",
contentType: "application/json", //必須有
dataType: "json", //表示返回值型別,不必須
data: JSON.stringify({'ids': '1'}),
success: function (jsonResult) {
alert(jsonResult);
}
});
後臺
public AjaxJson flfgNameQuery(@RequestBody entry et,HttpServletRequest req) {
String str = req.getParameter("ids");
System.out.println(str); //輸出null
System.out.println(et.getIds())//輸出1
}
public class entry {
String ids;
public String getIds() {
return ids;
}
public void setIds(String ids) {
this.ids = ids;
}
}
也可以使用JSONObject
public AjaxJson flfgNameQuery(@RequestBody JSONObject object,HttpServletRequest req) {
String str = req.getParameter("ids");
System.out.println(str); //輸出null
System.out.println(object.getXXX())//輸出1
}
總結:
當使用application/x-www-form-urlencoded時其實JSP會預設把我們的json資料認為是一個物件,而使用application/json時需要向後臺傳入一個JSON字串,所以要用JSON.stringify函式把JSON物件轉成json字串。