AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。POST 是 HTTP 方法之一,用于向服务器发送数据,通常用于提交表单或传输较大量的数据。
// 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 配置请求
xhr.open('POST', 'process.php', 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 = 'name=' + encodeURIComponent('John') + '&age=' + encodeURIComponent(30);
xhr.send(data);
$.ajax({
type: "POST",
url: "process.php",
data: {
name: "John",
age: 30
},
success: function(response) {
console.log(response);
// 处理服务器返回的数据
},
error: function(xhr, status, error) {
console.error(error);
}
});
<?php
// 检查是否是 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取 POST 数据
$name = isset($_POST['name']) ? $_POST['name'] : '';
$age = isset($_POST['age']) ? $_POST['age'] : '';
// 数据验证
if (empty($name) || empty($age)) {
http_response_code(400);
echo json_encode(['error' => 'Name and age are required']);
exit;
}
// 处理数据
$response = [
'status' => 'success',
'message' => 'Data received',
'data' => [
'name' => htmlspecialchars($name),
'age' => intval($age)
]
];
// 返回 JSON 响应
header('Content-Type: application/json');
echo json_encode($response);
} else {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
}
?>
原因:
解决方案:
php.ini
中 enable_post_data_reading
是否为 On原因:
解决方案:
原因:
解决方案:
fetch('process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({name: 'John', age: 30})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
axios.post('process.php', {
name: 'John',
age: 30
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
没有搜到相关的沙龙