【转】Ajax的content-Type
原文地址:http://www.pianshen.com/article/4339171883/
原文地址:https://blog.csdn.net/qq32933432/article/details/80817250
————————————————
版权声明:本文为CSDN博主「诺浅」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq32933432/article/details/80817250
contentType默认
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
一、 简单的JSON
var p = {name : 'luo', score : '100'}; $.ajax({ type: "post", url: "/role/contentTypeTest", dataType: 'json', data: p, error: function(request) { layer.alert('添加失败'); }, success: function(result) { layer.msg('保存成功'); } });

二、复杂的 JSON对像
var p = { name: 'yuwen', score: [ {'luo' : '100'}, {'lei' : '98'} ] }; $.ajax({ type: "post", url: "/role/contentTypeTest", dataType: 'json', data: p, error: function(request) { layer.alert('添加失败'); }, success: function(result) { layer.msg('保存成功'); } });

这个复杂对象, application/x-www-form-urlencoded 这种形式是没有办法将复杂的 JSON 组织成键值对形式。你传进去之后可以发送请求,但是服务端收到数据为空, 因为 ajax不知道怎样处理这个数据。
HTTP还可以自定义数据类型,于是就定义一种叫 application/json 的类型。我们 ajax 的复杂JSON数据,用 JSON.stringify序列化后然后发送,在服务器端接到然后用 JSON.parse 进行还原就行了。
var p = { name: 'yuwen', score: [ {'luo' : '100'}, {'lei' : '98'} ] }; $.ajax({ type: "post", url: "/role/contentTypeTest", dataType: 'json', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(p), error: function(request) { layer.alert('添加失败'); }, success: function(result) { layer.msg('保存成功'); } });

总结
"Content-Type": "application/x-www-form-urlencoded" // 适用于大部分情况 "Content-Type": "application/json" //适用于复杂JSON数据的提交 "Content-Type": "multipart/form-data" // 适用于文件上传

浙公网安备 33010602011771号