標籤:事件 chrome 執行 new set 資料 not 建立 ref
AJAX 投票
在下面的執行個體中,我們將示範一個投票程式,通過它,投票結果在網頁不進行重新整理的情況下被顯示。
執行個體解釋 - 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="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="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)中儲存來自投票程式的資料。
它儲存的資料如下所示:
- 3||4
複製
第一個數字表示 "Yes" 的投票數,第二個數字表示 "No" 的投票數。
注釋:請記得只允許您的 Web 服務器來編輯該文字檔。不要讓其他人獲得訪問權,除了 Web 服務器 (PHP)。
PHP 執行個體 - AJAX 投票