使用AJAX发起POST请求通常涉及到XMLHttpRequest对象或者现代的fetchAPI。以下是使用这两种方式的示例代码。
使用XMLHttpRequest的示例:
var xhr = new XMLHttpRequest();
xhr.open("POST", "your_server_endpoint", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功
console.log(xhr.responseText);
}
};
var data = "key1=value1&key2=value2";
xhr.send(data);使用fetchAPI的示例:
fetch("your_server_endpoint", {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({ key1: "value1", key2: "value2" })
}).then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));在这两个示例中,你需要替换your_server_endpoint为你的服务器端点,并且可以根据需要修改data变量中的键值对来发送你的数据。使用fetchAPI的示例中,URLSearchParams对象会自动处理数据的序列化。