最近在做项目交互的时候,刚开始向后台传递数据返回 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"的作用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对尊托云数网站的支持!
在Flash Player 10.1及以上版本中,adobe新增了全局错误处理程序UncaughtErrorEv...
本文转载自微信公众号「SH的全栈笔记」,作者SH。转载本文请联系SH的全栈笔记公...
大家好,我是狂聊君。 今天来聊一聊 Mysql 缓存池原理。 提纲附上,话不多说,直...
本文转载自微信公众号「SQL数据库」,作者丶平凡世界 。转载本文请联系开发公众...
CKeditor,以前叫FCKeditor,已经使用过好多年了,功能自然没的说。最近升级到3....
idea官方推送了2020.2.4版本的更新,那么大家最关心的问题来了,之前激活idea202...
本文实例讲述了AJAX+Servlet实现的数据处理显示功能。分享给大家供大家参考,具...
来源:DeepenStudy 漏洞文件:js.asp % Dimoblog setoblog=newclass_sys oblog.a...
前言 项目开发中不管是前台还是后台都会遇到烦人的null,数据库表中字段允许空值...
问题:我们在做flex的开发中,如果用到别人搭建好的框架,而别人的server名称往...