关于Ajax设置请求头
来源:12-2 ajax 的核心API - XMLHttpRequest

起飞啊飞
2022-08-22
老师,我想请问一下Ajax发送POST请求的时候不需要添加请求头吗?这样写是不是更加完整呢?
const xhr = new XMLHttpRequest()
xhr.open('POST', 'url地址')
//可能需要设置请求头?
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
const postData = {
name: 'zhangsan',
age: 20,
pw: 'xxx'
}
//转为JSON字符串的形式
xhr.send(JSON.stringify(postData))
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
写回答
1回答
-
如果你想发送的内容有格式,肯定要添加 header ,即 content-type
不过,我看你代码,你想发送一个 JSON 格式的,那么应该写 'application/json' 才对
022022-08-23
相似问题