首页 > web前端 > js教程 > 正文

ajax中设置contentType: "application/json"的作用(图文教程)

亚连
发布: 2018-05-21 15:50:38
原创
4279 人浏览过

这篇文章主要介绍了ajax中设置contentType: “application/json”的作用,需要的朋友可以参考下

最近在做项目交互的时候,刚开始向后台传递数据返回 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 PHP JavaScript MySQL实现简易无刷新在线聊天室

jQuery+Ajax验证用户名步骤详解

Yii2表单事件之Ajax提交实现方法

以上是ajax中设置contentType: "application/json"的作用(图文教程)的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!