美文网首页
ajax中contentType:"application/js

ajax中contentType:"application/js

作者: 西谷haul | 来源:发表于2021-10-07 13:25 被阅读0次

ajax请求参数为json格式两种写法
第一种:不使用contentType: “application/json”则data可以是对象

data:{
“param”:”param”
}

第二种:使用contentType: “application/json”则data只能是json字符串,contentType 主要设置你发送给服务器的格式,可以使用json.stringify()函数来将对象解析为字符串格式。


$.ajax({
   type:'POST',
   url: 'api/test/ajaxTest',
   data:JSON.stringify({"queryType":"test"}),
   contentType:"json/application",
   dataType: 'JSON',
    success:function (data) {

    },
    error:function (data) {

    }
 })

使用JSON.stringify()不使用contentType时,如果前后台通过json格式传递参数,很容易前端不报错,后台接收不到数据
没有使用contentType,请求时后台接受参数为null

image.png

前端传递参数:


image.png

遇到这个问题,加上contentType:”application/json”一般就解决了。

如果是post请求传的是字符串,可以不使用contentType和JSON.stringify()就可以,如下:


image.png image.png

相关文章

网友评论

      本文标题:ajax中contentType:"application/js

      本文链接:https://www.haomeiwen.com/subject/saxznltx.html