1. 创建XMLHttpRequest对象:
var xhr = new XMLHttpRequest();
2. 创建请求:
xhr.open('POST', 'example.php', true);
3. 设置请求头:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
4. 发送请求:
xhr.send(data);
5. 监听状态变化:
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 成功接收到响应
console.log(xhr.responseText);
}
};
1. 创建XMLHttpRequest对象:
var xhr = new XMLHttpRequest();
2. 创建请求:
xhr.open('POST', 'example.php', true);
3. 设置请求头:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
4. 发送请求:
xhr.send(data);
5. 在PHP中处理请求:
<?php
// 获取请求数据
$data = $_POST['data'];
// 做一些处理
// 返回响应
echo '处理结果';
?>
需要注意的是,在PHP中处理完请求后,需要将结果返回给前端。可以使用echo语句将结果输出。