// 使用 XMLHttpRequest 发送 POST 请求
function sendPostRequest(url, data) {
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open("POST", url, true);
// 设置请求头,指定内容类型为 application/json
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// 定义响应处理函数
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("服务器响应: ", xhr.responseText);
}
};
// 将数据转换为 JSON 字符串并发送请求
xhr.send(JSON.stringify(data));
}
// 示例调用
var url = "https://example.com/api";
var data = { key1: "value1", key2: "value2" };
sendPostRequest(url, data);
var xhr = new XMLHttpRequest();
创建了一个新的 XMLHttpRequest 实例,用于与服务器进行通信。xhr.open("POST", url, true);
配置了请求的类型(POST)、目标 URL 和是否异步(true 表示异步)。xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
指定了请求的内容类型为 JSON。xhr.onreadystatechange
监听请求状态的变化,当请求完成且状态码为 200 时,输出服务器的响应。xhr.send(JSON.stringify(data));
将数据转换为 JSON 字符串并发送到服务器。这个例子展示了如何使用原生 JavaScript 发送一个简单的 POST 请求。
上一篇:js 数组 排序
下一篇:js post 请求
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站