百度的AI回答了一个案例:
var xhr = new XMLHttpRequest();
var url = "your_endpoint_url"; // 替换为你的API端点
var data = JSON.stringify({key1: "value1",key2: "value2"
});xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {// 请求成功var response = JSON.parse(xhr.responseText);console.log(response);}
};xhr.send(data);
我觉得已经回答得不错的了,这里要注意两点:
1.xhr.setRequestHeader("Content-Type", "application/json");不可缺少;
2.xhr.send(data);的时候,里面这个data,必须是字符串的,所以上面用JSON.stringify()转成了字符串来传输到后端。
参考: