PHP 新手入門之AJAX投票

AJAX 投票

在下面的實例中,我們將示範一個投票程序,透過它,投票結果在網頁不進行刷新的情況下被顯示

首先我們寫一個php的文件,程式碼如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
<script>
function getVote(int) {
  if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari 执行代码
    xmlhttp=new XMLHttpRequest();
  } else {
    // 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","demo.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() 函數會執行以下步驟:

建立XMLHttpRequest 物件

建立在伺服器回應就緒時執行的函數

向伺服器上的檔案傳送請求

請注意新增至URL 末端的參數(q)(包含下拉清單的內容)

然後建立一個demo.php的檔案 程式碼如下:

<?php
$vote = htmlspecialchars($_REQUEST['vote']);

// 获取文件中存储的数据
$filename = "poll_result.txt";
$content = file($filename);

// 将数据分割到数组中
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0){
  $yes = $yes + 1;
}

if ($vote == 1){
  $no = $no + 1;
}

// 插入投票数据
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>结果:</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>

程式碼解釋:

當所選的值從JavaScript傳送到PHP 檔案時,會發生:

1. 取得"poll_result.txt" 檔案的內容

2. 把檔案內容放入變量,並累積變數按累加1

3. 把結果寫入"poll_result.txt" 檔案

4. 輸出圖形化的投票結果


繼續學習
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script> function getVote(int) { if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 执行代码 xmlhttp=new XMLHttpRequest(); } else { // 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","7_2.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>
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!