AJAX 投票

在下面的實(shí)例中,我們將演示一個(gè)投票程序,通過它,投票結(jié)果在網(wǎng)頁不進(jìn)行刷新的情況下被顯示。

你喜歡 PHP 和 AJAX 嗎?


實(shí)例解釋 - HTML 頁面

當(dāng)用戶選擇上面的某個(gè)選項(xiàng)時(shí),會(huì)執(zhí)行名為 "getVote()" 的函數(shù)。該函數(shù)由 "onclick" 事件觸發(fā)。

poll.html 文件代碼如下:

<html>
<head>
<meta charset="utf-8">
<title>php中文網(wǎng)(php.cn)</title>
<script>
function getVote(int) {
  if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari 執(zhí)行代碼
    xmlhttp=new XMLHttpRequest();
  } else {
    // IE6, IE5 執(zhí)行代碼
    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>你喜歡 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>

getVote() 函數(shù)會(huì)執(zhí)行以下步驟:

  • 創(chuàng)建 XMLHttpRequest 對(duì)象

  • 創(chuàng)建在服務(wù)器響應(yīng)就緒時(shí)執(zhí)行的函數(shù)

  • 向服務(wù)器上的文件發(fā)送請(qǐng)求

  • 請(qǐng)注意添加到 URL 末端的參數(shù)(q)(包含下拉列表的內(nèi)容)


PHP 文件

上面這段通過 JavaScript 調(diào)用的服務(wù)器頁面是名為 "poll_vote.php" 的 PHP 文件:

<?php
$vote = htmlspecialchars($_REQUEST['vote']);
// 獲取文件中存儲(chǔ)的數(shù)據(jù)
$filename = "poll_result.txt";
$content = file($filename);
// 將數(shù)據(jù)分割到數(shù)組中
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0)
{
  $yes = $yes + 1;
}
if ($vote == 1)
{
  $no = $no + 1;
}
// 插入投票數(shù)據(jù)
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>結(jié)果:</h2>
<table>
  <tr>
  <td>是:</td>
  <td>
  <span style="display: inline-block; background-color:green;
      width:<?php echo(100*round($yes/($no+$yes),2)); ?>px;
      height:20px;" ></span>
  <?php echo(100*round($yes/($no+$yes),2)); ?>%
  </td>
  </tr>
  <tr>
  <td>否:</td>
  <td>
  <span style="display: inline-block; background-color:red;
      width:<?php echo(100*round($no/($no+$yes),2)); ?>px;
      height:20px;"></span>
  <?php echo(100*round($no/($no+$yes),2)); ?>%
  </td>
  </tr>
</table>

當(dāng)所選的值從 JavaScript 發(fā)送到 PHP 文件時(shí),將發(fā)生:

  1. 獲取 "poll_result.txt" 文件的內(nèi)容

  2. 把文件內(nèi)容放入變量,并向被選變量累加 1

  3. 把結(jié)果寫入 "poll_result.txt" 文件

  4. 輸出圖形化的投票結(jié)果


文本文件

文本文件(poll_result.txt)中存儲(chǔ)來自投票程序的數(shù)據(jù)。

它存儲(chǔ)的數(shù)據(jù)如下所示:

3||4

第一個(gè)數(shù)字表示 "Yes" 的投票數(shù),第二個(gè)數(shù)字表示 "No" 的投票數(shù)。

注釋:請(qǐng)記得只允許您的 Web 服務(wù)器來編輯該文本文件。不要讓其他人獲得訪問權(quán),除了 Web 服務(wù)器 (PHP)。

相關(guān)視頻教程推薦:《AJAX教程http://ipnx.cn/course/list/25.html