XMLHttpRequest
是一個用于創(chuàng)建異步 HTTP 請求的 JavaScript 對象。通過使用 XMLHttpRequest
,你可以實(shí)現(xiàn)客戶端與服務(wù)器之間的實(shí)時通信。以下是一個簡單的示例,展示了如何使用 XMLHttpRequest
實(shí)現(xiàn)實(shí)時通信:
index.html
:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XMLHttpRequest Real-time Communication</title>
</head>
<body>
<h1>XMLHttpRequest Real-time Communication</h1>
<button id="sendRequest">Send Request</button>
<ul id="responseList"></ul>
<script src="main.js"></script>
</body>
</html>
main.js
:document.getElementById('sendRequest').addEventListener('click', sendRequest);
function sendRequest() {
const xhr = new XMLHttpRequest();
const url = 'server.php'; // 你的服務(wù)器端腳本地址
// 設(shè)置請求類型和服務(wù)器地址
xhr.open('GET', url, true);
// 設(shè)置請求完成時的回調(diào)函數(shù)
xhr.onload = function () {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
addResponseToList(response);
sendRequest(); // 遞歸調(diào)用以實(shí)現(xiàn)實(shí)時通信
} else {
console.error('Error:', xhr.statusText);
}
};
// 發(fā)送請求
xhr.send();
}
function addResponseToList(response) {
const responseList = document.getElementById('responseList');
const listItem = document.createElement('li');
listItem.textContent = response.message;
responseList.appendChild(listItem);
}
<?php
header('Content-Type: application/json');
// 這里可以連接數(shù)據(jù)庫或執(zhí)行其他操作來獲取實(shí)時數(shù)據(jù)
$message = 'Hello from server!';
// 發(fā)送 JSON 格式的響應(yīng)
echo json_encode(['message' => $message]);
server.php
部署到一個支持 PHP 的 Web 服務(wù)器上,并確保 index.html
和 main.js
文件位于同一目錄下。現(xiàn)在,當(dāng)你在瀏覽器中打開 index.html
并點(diǎn)擊 “Send Request” 按鈕時,客戶端將通過 XMLHttpRequest
向服務(wù)器發(fā)送請求,服務(wù)器將返回一個 JSON 格式的響應(yīng)??蛻舳私邮盏巾憫?yīng)后,將其添加到列表中,并再次發(fā)送請求以實(shí)現(xiàn)實(shí)時通信。