在<script></script>发起POST请求
时间: 2023-04-01 11:01:31 浏览: 73
可以使用 JavaScript 中的 XMLHttpRequest 对象来发起 POST 请求。具体的实现方式可以参考以下代码:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/api', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
var data = {
name: 'John',
age: 30
};
xhr.send(JSON.stringify(data));
```
其中,`xhr.open('POST', 'http://example.com/api', true)` 表示使用 POST 方法向 `http://example.com/api` 发起请求,第三个参数为 true 表示使用异步方式。`xhr.setRequestHeader('Content-Type', 'application/json')` 表示请求体的类型为 JSON 格式。`xhr.onreadystatechange` 表示当请求状态发生变化时的回调函数,当状态为 4(请求完成)且状态码为 200(请求成功)时,输出响应内容。最后,使用 `xhr.send(JSON.stringify(data))` 发送请求体数据。