最近在做項目交互的時候,剛開始向后臺傳遞數據返回 415 ,后來百度添加了 contentType:“application/json“ 之后返回400,然后把傳輸的數據格式改為json字符串就傳輸成功了,現在我們來看看 contentType:“application/json“的作用:
添加 contentType:“application/json“之后,向后臺發(fā)送數據的格式必須為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“的時候可以向后天發(fā)送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)
}
})
補充:下面看下$.ajax中contentType: “application/json” 的用法
不使用contentType: “application/json”則data可以是對象
$.ajax({
url: actionurl,
type: "POST",
datType: "JSON",
data: { id: nodeId },
async: false,
success: function () {}
});
使用contentType: “application/json”則data只能是json字符串
$.ajax({
url: actionurl,
type: "POST",
datType: "JSON",
contentType: "application/json"
data: "{'id': " + nodeId +"}",
async: false,
success: function () {}
});
總結
以上所述是小編給大家介紹的ajax中設置contentType: "application/json"的作用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
您可能感興趣的文章:- $.ajax中contentType: “application/json” 的用法詳解