PHP 是一种广泛使用的服务器端脚本语言,特别适用于 Web 开发。AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
server.php
)<?php
// 获取请求参数
$name = $_POST['name'] ?? '';
// 返回响应
$response = [
'status' => 'success',
'message' => "Hello, $name!"
];
header('Content-Type: application/json');
echo json_encode($response);
?>
index.html
)<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP + AJAX Example</title>
<script>
function sendMessage() {
var name = document.getElementById('name').value;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'server.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
document.getElementById('result').innerText = response.message;
}
};
xhr.send('name=' + encodeURIComponent(name));
}
</script>
</head>
<body>
<h1>PHP + AJAX Example</h1>
<input type="text" id="name" placeholder="Enter your name">
<button onclick="sendMessage()">Send</button>
<p id="result"></p>
</body>
</html>
application/json
。JSON.parse()
。通过以上示例和解释,你应该能够理解 PHP 和 AJAX 的基本用法及其应用场景。如果有更多具体问题,可以进一步提问。
领取专属 10元无门槛券
手把手带您无忧上云