关于 ajax Content-Type 的问题

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 () {

           },
       })

猜你喜欢

转载自blog.csdn.net/qh870754310/article/details/85088510