本文目录导读:

在 PHP 中实现"无刷新"更新,主要有以下几种方案:
AJAX 方案(最常用)
原生 JavaScript + PHP
<?php
// server.php
if (isset($_POST['action'])) {
echo json_encode(['status' => 'success', 'data' => '服务器返回数据']);
exit;
}
?>
<!-- client.html -->
<!DOCTYPE html>
<html>
<head>
<script>
function fetchData() {
// 创建 XMLHttpRequest 对象
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) {
document.getElementById('result').innerHTML = xhr.responseText;
}
};
xhr.send('action=getData¶m=value');
}
</script>
</head>
<body>
<div id="result">初始内容</div>
<button onclick="fetchData()">点击加载</button>
</body>
</html>
jQuery + PHP
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// GET 请求
$.ajax({
url: 'server.php',
type: 'GET',
data: { action: 'getData' },
success: function(response) {
$('#result').html(response);
},
error: function(xhr, status, error) {
console.error('错误:', error);
}
});
// POST 请求
$.post('server.php', { action: 'save' }, function(data) {
$('#result').html(data);
});
// 简化写法
$.get('server.php', { action: 'getData' }, function(data) {
$('#result').html(data);
});
</script>
Fetch API 方案(现代方式)
<script>
async function fetchData() {
try {
const response = await fetch('server.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'getData', id: 123 })
});
const data = await response.json();
document.getElementById('result').innerHTML = data.content;
} catch (error) {
console.error('请求失败:', error);
}
}
</script>
WebSocket 方案(实时通信)
服务端(需要安装 Ratchet)
<?php
// server.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require 'vendor/autoload.php';
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "新连接: {$conn->resourceId}\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
$client->send($msg);
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "连接关闭\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$server = \Ratchet\Server\IoServer::factory(
new \Ratchet\Http\HttpServer(
new \Ratchet\WebSocket\WsServer(new Chat())
),
8080
);
$server->run();
?>
客户端
<script>
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
console.log('连接成功');
ws.send('发送消息');
};
ws.onmessage = function(event) {
document.getElementById('result').innerHTML = event.data;
};
</script>
SSE(Server-Sent Events)方案
<?php
// stream.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while (true) {
$time = date('H:i:s');
echo "data: 当前时间: {$time}\n\n";
ob_flush();
flush();
sleep(1);
}
?>
<script>
var source = new EventSource('stream.php');
source.onmessage = function(event) {
document.getElementById('result').innerHTML = event.data;
};
</script>
Axios 方案(推荐)
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// GET 请求
axios.get('server.php', {
params: { action: 'getData', id: 123 }
})
.then(response => {
document.getElementById('result').innerHTML = response.data;
})
.catch(error => {
console.error('请求失败:', error);
});
// POST 请求
axios.post('server.php', {
action: 'save',
data: { name: '张三', age: 25 }
})
.then(response => {
document.getElementById('result').innerHTML = response.data;
});
</script>
完整示例:实时搜索
<?php
// search.php
if (isset($_GET['q'])) {
$keyword = $_GET['q'];
// 模拟数据库查询
$results = [
'php' => 'PHP教程',
'javascript' => 'JavaScript教程',
'mysql' => 'MySQL教程',
'ajax' => 'AJAX教程'
];
$output = '<ul>';
foreach ($results as $key => $value) {
if (strpos($key, $keyword) !== false) {
$output .= "<li>{$value}</li>";
}
}
$output .= '</ul>';
echo $output;
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="search" placeholder="搜索...">
<div id="results"></div>
<script>
$(document).ready(function() {
$('#search').on('keyup', function() {
var keyword = $(this).val();
if (keyword.length > 0) {
$.get('search.php', { q: keyword }, function(data) {
$('#results').html(data);
});
} else {
$('#results').html('');
}
});
});
</script>
</body>
</html>
选择建议
| 方案 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| AJAX | 常规数据请求 | 兼容性好,简单 | 只能单方向通信 |
| Fetch API | 现代浏览器 | Promise语法,更简洁 | 兼容性稍差 |
| WebSocket | 实时聊天/游戏 | 双向通信,实时性高 | 服务端配置复杂 |
| SSE | 服务器推送通知 | 自动重连,单向推送 | 只能服务器到客户端 |
| Axios | 复杂项目 | 功能强大,拦截器 | 需要引入第三方库 |
推荐使用:对于大多数场景,使用 Axios + PHP 是最佳选择,既能保持代码简洁,又能处理复杂逻辑。