xmlhttprequest发送post请求传参
时间: 2024-12-28 14:14:59 浏览: 26
### 使用XMLHttpRequest发送带有参数的POST请求
为了使用`XMLHttpRequest`对象发送带参数的POST请求,在创建该对象实例之后,需调用其`open()`方法指定HTTP动词为"POST"以及目标URL。随后通过设置`setRequestHeader()`来定义必要的头部字段,特别是对于POST请求而言,应该设定`Content-Type`为`application/x-www-form-urlencoded`以便服务器能够正确解析表单数据[^1]。
下面是一个完整的例子展示如何构建这样的请求:
```javascript
function sendPostRequest(url, params) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
// 设置适当的header
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
// 发送实际的数据作为字符串形式的键值对
xhr.send(params);
}
```
在这个函数里,`params`应被格式化成查询字符串的形式,比如`'name=John&age=30'`。如果要发送JSON类型的payload,则需要调整`Content-Type`头至`application/json;charset=UTF-8`并将JavaScript对象转换成JSON字符串再传递给`send()`方法。
阅读全文
相关推荐


















