最近在做項目交互的時候,剛開始向後臺傳遞數據返回415,後來百度添加了 contentType:“application/json“之後返回400,然後把傳輸的數據格式改爲json字符串就傳輸成功了,現在我們來看看 contentType:“application/json“的作用:
添加 contentType:“application/json“之後,向後臺發送數據的格式必須爲json字符串
$.ajax({
type: "post",
url: "mobile/notice/addMessageInfo.jspx",
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對象形式
$.ajax({
type: "post",
url: "mobile/notice/addMessageInfo.jspx",
data:{name:'zhangsan',age:'15'},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(msg) {
console.log(msg)
}
})
另外,當向後臺傳遞複雜json的時候,同樣需要添加 contentType:“application/json“,然後將數據轉化爲字符串
var data = {
uploadarray: uploadarray,
messageInfo: {
messageTitle: messageTitle,
messageContent: messageContent,
publisher: publisher
},
userId: userId
}
$.ajax({
type: 'post',
url: "mobile/notice/addMessageInfo.jspx",
contentType: 'application/json',
data: JSON.stringify(data),
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(msg) {
console.log(msg)
}
})