透過 AJAX 技術,使用者點選選項後無需重新整理頁面,即可將投票送至伺服器並即時顯示結果圖表。本範例採用純 JavaScript (XMLHttpRequest) + PHP + 文字檔儲存,適合學習 AJAX 基礎流程。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX 投票範例</title>
<script>
function getVote(val) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('poll').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'poll_vote.php?vote=' + val, true);
xhr.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>你喜歡 PHP 和 AJAX 嗎?</h3>
<form>
是: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"><br>
否: <input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
<?php
$vote = isset($_REQUEST['vote']) ? (int)$_REQUEST['vote'] : -1;
if ($vote !== 0 && $vote !== 1) {
exit('無效參數');
}
$filename = 'poll_result.txt';
// 讀取現有資料
$content = @file_get_contents($filename);
if ($content === false) {
$yes = $no = 0;
} else {
list($yes, $no) = explode('||', $content);
}
// 累加
if ($vote === 0) $yes++;
else $no++;
// 寫回檔案 (建議加檔案鎖定)
$fp = fopen($filename, 'w');
if ($fp) {
fwrite($fp, "$yes||$no");
fclose($fp);
}
// 輸出結果圖表
$total = $yes + $no;
$yesPct = $total ? round(100 * $yes / $total, 2) : 0;
$noPct = $total ? round(100 * $no / $total, 2) : 0;
?>
<h2>結果:</h2>
<table>
<tr><td>是:</td><td>
<span style="display:inline-block;background:green;width:<?php echo $yesPct; ?>px;height:20px;"></span>
<?php echo $yesPct; ?>%
</td></tr>
<tr><td>否:</td><td>
<span style="display:inline-block;background:red;width:<?php echo $noPct; ?>px;height:20px;"></span>
<?php echo $noPct; ?>%
</td></tr>
</table>
3||4
第一個數字為「是」票數,第二個為「否」票數。
onclick="getVote(this.value)"。getVote() 建立 XMLHttpRequest,送出 GET 請求至 poll_vote.php?vote=0/1。onreadystatechange 收到回應,將 #poll 內容替換為結果。flock() 或改用資料庫 (SQLite/MySQL) 避免並發寫入覆蓋。$_REQUEST['vote'] 僅允許 0/1。htmlspecialchars()。fetch() API、axios 或 jQuery $.ajax() 簡化前端代碼。