$.ajax 中的contentType类型

前言

今天在搞项目的时候遇到一个问题,$.ajax 设置数据类型 applicaiton/json之后,服务器端(express)就拿不到数据,遂解决后将问题以及问题原因整理下来。

正文

$.ajax contentType 和 dataType , contentType 主要设置你发送给服务器的格式,dataType设置你收到服务器数据的格式。

在http 请求中,get 和 post 是最常用的。在 jquery 的 ajax 中, contentType都是默认的值:application/x-www-form-urlencoded,这种格式的特点就是,name/value 成为一组,每组之间用 & 联接,而 name与value 则是使用 = 连接。如: wwwh.baidu.com/q?key=fdsa&lang=zh 这是get , 而 post 请求则是使用请求体,参数不在 url 中,在请求体中的参数表现形式也是: key=fdsa&lang=zh的形式。

一般,不带嵌套类型JSON:

data:{
  name:'zhangsan',
  age:'15' 
}

如果是一些复杂一点的带嵌套的JSON:

data:{
  data: {
    a: [{
      x: 2
    }]
  }
}

application/x-www-form-urlencoded 是没有办法将复杂的 JSON 组织成键值对形式,你可以发送请求,但是服务端收到数据为空, 因为 ajax 不知道怎样处理这个数据。

解决方法:
发现 http 还可以自定义数据类型,于是就定义一种叫 application/json 的类型。这种类型是 text , 我们 ajax 的复杂JSON数据,用 JSON.stringify序列化后,然后发送,在服务器端接到然后用 JSON.parse 进行还原就行了,这样就能处理复杂的对象了。

$.ajax({
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({a: [{b:1, a:1}]})
})

总结

“application/json“的作用:
添加 contentType:“application/json“之后,向后台发送数据的格式必须为json字符串

$.ajax({
    type: "post",
    url:  "",
    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:  "",
    data:{  
        name:'zhangsan',
        age:'15'
    },
    dataType: "json",
    success: function(data) {
        console.log(data);
    },
    error: function(msg) {
        console.log(msg)
    }
})

另外,当向后台传递复杂json的时候,同样需要添加 contentType:“application/json“,然后将数据转化为字符串

var parm = {
    a: a,
    b: {
        c: c,
        d: d,
        e: e
    },
    f: f
}

$.ajax({  
    type: 'post',
    url: "",
    contentType: 'application/json',
    data: JSON.stringify(parm),
    dataType: "json",
    success: function(data) {
        console.log(data);
    },
    error: function(msg) {
        console.log(msg)
    }
})

猜你喜欢

转载自blog.csdn.net/weixin_33853794/article/details/86959031