给接口发数据时使用
$.ajax({
type: 'post',
url: 'xxxx',
data: {timestamp},
dataType: 'json'
})
此时接口的响应头能正确返回json数据,Content-Type为application/json,
而使用原生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,
请问为什么jQuery设置了dataType就能正确返回json格式,而原生ajax返回的就是xml呢?是哪个地方写的不对吗?求各位大佬指点~~~
已经自行解决,原来需要请求头也要设置json格式才行,感谢大家