关于$.ajax设置dataType的问题

给接口发数据时使用

$.ajax({
    type: 'post',
    url: 'xxxx', 
    data: {timestamp},
    dataType: 'json'
})

此时接口的响应头能正确返回json数据,Content-Type为application/json,
image.png

而使用原生js发送请求

var xhr = new XMLHttpRequest()

xhr.open('post', url, true)
xhr.responseType = 'json'    //设置响应类型
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(timestamp)

xhr.onload = function() {
  if(xhr.readyState==4 && xhr.status == 200) {
    console.log(xhr.response)
  }
}

接口返回的格式总是为Content-Type: application/xml,
image.png
请问为什么jQuery设置了dataType就能正确返回json格式,而原生ajax返回的就是xml呢?是哪个地方写的不对吗?求各位大佬指点~~~

阅读 1.8k
1 个回答

已经自行解决,原来需要请求头也要设置json格式才行,感谢大家

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题