AJAX是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。它允许:
PHP是一种服务器端脚本语言,特别适合Web开发:
// JavaScript (AJAX)
let xhr = new XMLHttpRequest();
xhr.open('GET', 'process.php?param1=value1', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
// process.php
<?php
$param = $_GET['param1'];
echo "Received: " . htmlspecialchars($param);
?>
// JavaScript
let xhr = new XMLHttpRequest();
xhr.open('POST', 'process.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
};
xhr.send('name=John&age=30');
// process.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo "Hello, $name. You are $age years old.";
?>
// JavaScript
fetch('api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({username: 'john', password: '1234'})
})
.then(response => response.json())
.then(data => console.log(data));
// api.php
<?php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$response = [
'status' => 'success',
'user' => $data['username']
];
echo json_encode($response);
?>
原因:PHP文件路径不正确或服务器配置问题 解决:
原因:浏览器的同源策略限制 解决:
// 在PHP文件中添加CORS头
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');
原因:未正确设置请求头或数据格式 解决:
file_get_contents('php://input')
获取原始POST数据原因:字符编码不一致 解决:
header('Content-Type: text/html; charset=utf-8');
// 或对于JSON
header('Content-Type: application/json; charset=utf-8');
$clean_input = filter_var($_POST['input'], FILTER_SANITIZE_STRING);
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$_POST['email']]);
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('Invalid CSRF token');
}
}
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
ob_start('ob_gzhandler');
AJAX与PHP的结合为现代Web应用提供了强大的交互能力,合理使用可以显著提升用户体验和应用性能。