今天在搞項目的時候遇到一個問題,$.ajax
設置數據類型 applicaiton/json
以後,服務器端(express)就拿不到數據,遂解決後將問題以及問題緣由整理下來。jquery
$.ajax contentType 和 dataType , contentType 主要設置你發送給服務器的格式,dataType設置你收到服務器數據的格式。ajax
在http 請求中,get 和 post 是最經常使用的。在 jquery 的 ajax 中, contentType都是默認的值:application/x-www-form-urlencoded
,這種格式的特色就是,name/value 成爲一組,每組之間用 & 聯接,而 name與value 則是使用 = 鏈接。如: wwwh.baidu.com/q?key=fdsa&lang=zh
這是get , 而 post 請求則是使用請求體,參數不在 url 中,在請求體中的參數表現形式也是: key=fdsa&lang=zh
的形式。express
通常,不帶嵌套類型JSON:json
data:{
name:'zhangsan',
age:'15'
}
複製代碼
若是是一些複雜一點的帶嵌套的JSON:bash
data:{
data: {
a: [{
x: 2
}]
}
}
複製代碼
application/x-www-form-urlencoded
是沒有辦法將複雜的 JSON 組織成鍵值對形式,你能夠發送請求,可是服務端收到數據爲空, 由於 ajax 不知道怎樣處理這個數據。服務器
解決方法:app
發現 http 還能夠自定義數據類型,因而就定義一種叫 application/json 的類型。這種類型是 text , 咱們 ajax 的複雜JSON數據,用 JSON.stringify序列化後,而後發送,在服務器端接到而後用 JSON.parse 進行還原就好了,這樣就能處理複雜的對象了。post
$.ajax({
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({a: [{b:1, a:1}]})
})
複製代碼
「application/json「的做用: 添加 contentType:「application/json「以後,向後臺發送數據的格式必須爲json字符串ui
$.ajax({
type: "post",
url: "",
contentType: "application/json",
data:"{'name':'zhangsan','age':'15'}",
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(msg) {
console.log(msg)
}
})
複製代碼
不添加 contentType:「application/json「的時候能夠向後臺發送json對象形式url
$.ajax({
type: "post",
url: "",
data:{
name:'zhangsan',
age:'15'
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(msg) {
console.log(msg)
}
})
複製代碼
另外,當向後臺傳遞複雜json的時候,一樣須要添加 contentType:「application/json「
,而後將數據轉化爲字符串
var parm = {
a: a,
b: {
c: c,
d: d,
e: e
},
f: f
}
$.ajax({
type: 'post',
url: "",
contentType: 'application/json',
data: JSON.stringify(parm),
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(msg) {
console.log(msg)
}
})
複製代碼