PHP 實例 - AJAX 投票
AJAX 投票
在下面的實例中,我們將演示一個投票程序,通過它,投票結果在網頁不進行刷新的情況下被顯示。
Do you like PHP and AJAX so far?
實例解釋 - HTML 頁面
當用戶選擇上面的某個選項時,會執行名為 "getVote()" 的函數。該函數由 "onclick" 事件觸發:
<html>
<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("poll").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
getVote() 函數會執行以下步驟:
- 創建 XMLHttpRequest 對象
- 創建在服務器響應就緒時執行的函數
- 向服務器上的文件發送請求
- 請注意添加到 URL 末端的參數(q)(包含下拉列表的內容)
PHP 文件
上面這段通過 JavaScript 調用的服務器頁面是名為 "poll_vote.php" 的 PHP 文件:
<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0)
{
$yes = $yes + 1;
}
if ($vote == 1)
{
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="/upload/help/poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="/upload/help/poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
當所選的值從 JavaScript 發送到 PHP 文件時,將發生:
- 獲取 "poll_result.txt" 文件的內容
- 把文件內容放入變量,并向被選變量累加 1
- 把結果寫入 "poll_result.txt" 文件
- 輸出圖形化的投票結果
文本文件
文本文件(poll_result.txt)中存儲來自投票程序的數據。
它存儲的數據如下所示:
第一個數字表示 "Yes" 的投票數,第二個數字表示 "No" 的投票數。
注釋:請記得只允許您的 Web 服務器來編輯該文本文件。不要讓其他人獲得訪問權,除了 Web 服務器 (PHP)。