您的位置:首页 > 其它

关于 ajax Content-Type 的问题 贼拉有用的!!!

2017-12-19 10:30 295 查看

之前我写ajax根本就没有去关注响应头什么的 只是很简单的用而已 后来发现其实没那么简单

Content-Type 指的是发送至服务器的数据类型,而data-Type定义的是服务器返回的数据类型.此处应有图



上面那个红圈是Content-Type控制的数据类型 ,下面那个红圈是data-Type控制的数据类型

如果不指定ContentType,则一般情况默认为text/html,表单数据默认为application/x-www-form-urlencoded。

如果是 type: “GET”的话,以上三种都可以,因为GET类型的参数是紧跟在url后面,与Content-Type无关

如果是 type: “POST”的话,data数据是由form表单提交,此时就必须把Content-Type设为application/x-www-form-urlencoded(也可以不指定content-Type,因为表单提交默认是application/x-www-form-urlencoded),否则后台是无法接收到数据的。

contentType数据类型的不同 data里面所传递的数据类型也不同

如果是不使用contentType: “application/json”则data可以是对象

*

$.ajax({
type: "GET",
url: "/SmartStrip/InsertRow/GetDeviceList",
data: {

},
dataType: 'JSON',
success: function (data) {
console.log(data);
},
error: function () {

},
})


如果是使用contentType: “application/json”则data只能是json形式的字符串,需自行拼接

$.ajax({
type: "POST",
beforeSend: function (request) {
request.setRequestHeader("Authorization",Authorization);
},
url: url,
dataType: 'JSON',
contentType: "application/json",
data: '{'
+ '"name":"' + name + '",'
+ '"idsn":"' + idsn + '",'
+ '"brand":"' + brand + '",'
+ '"model":"' + model + '",'
+ '"pid":"' + pid + '",'
+ '"baseID":"' + baseID + '",'
+ '"areaID":"' + areaID + '"'
+ '}',
success: function (data) {
console.log(data);
},
error: function () {

},
})


哇咔咔 ~~ 写完了~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: