菜单

$.ajax中contentType: “application/json” 的用法

2018年12月19日 - Ajax

新近当开项目相的早晚,刚起先于后台传递数据重临 415 ,后来百度添加了
contentType:“application/json“
之后回到400,然后拿传输的多寡格式改吧json字符串就传成功了,现在大家来看望
contentType:“application/json“的意:

非利用contentType: “application/json”则data可以是目的

增补加
contentType:“application/json“之后,向后台发送数据的格式必须为json字符串

$.ajax({
url: actionurl,
type: “POST”,
datType: “JSON”,
data: { id: nodeId },
async: false,
success: function () {}
});

$.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)
  }
})
1
2
3
4
5
6
7
8

莫上加 contentType:“application/json“的下可以于先天发送json对象情势

使用contentType: “application/json”则data只能是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)
  }
})

$.ajax({
url: actionurl,
type: “POST”,
datType: “JSON”,
contentType: “application/json”
data: “{‘id’: ” + nodeId +”}”,
async: false,
success: function () {}
});

其余,当为后台传递复杂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”的用意,希望对大家有所助,即使我们发出另问题请于自身留言,小编会及时过来我们之。在斯吧异常感谢大家对剧本的寒网站的支撑!

汝可能感兴趣之稿子:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图