欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ajax中设置contentType: "application/json"的作用

程序员文章站 2022-06-17 17:03:27
最近在做项目交互的时候,刚开始向后台传递数据返回 415 ,后来百度添加了 contenttype:“application/json“ 之后返回400,然后把传输的数据格...

最近在做项目交互的时候,刚开始向后台传递数据返回 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)
  }
})

补充:下面看下$.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"的作用,希望对大家有所帮助