溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP+AJAX如何實現(xiàn)投票器功能

發(fā)布時間:2021-07-10 09:51:55 來源:億速云 閱讀:128 作者:小新 欄目:開發(fā)技術

這篇文章主要為大家展示了“PHP+AJAX如何實現(xiàn)投票器功能”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“PHP+AJAX如何實現(xiàn)投票器功能”這篇文章吧。

投票器

新建文件【 AJAX投票.html】

<html>
<head>
  <script type="text/javascript">
    // 這里是js代碼
    function getVote(int) {
      if (window.XMLHttpRequest) {
        // 創(chuàng)建 XMLHttpRequest 對象
        // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行的代碼
        xmlhttp = new XMLHttpRequest();
      } else {
        //IE6, IE5 瀏覽器執(zhí)行的代碼
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      // 監(jiān)聽響應
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState ==4 && xmlhttp.status == 200) {
          // 找到 id 為 poll 的控件
          document.getElementById('poll').innerHTML = xmlhttp.responseText;
        }
      }
      // 向PHP腳本傳遞主要參數(shù)q
      xmlhttp.open("GET", "poll_vote.php?q=" + int, true);
      xmlhttp.send();
    }
  </script>
</head>
<body>
  <div id="poll">
    <h4>你喜歡吃嗎?</h4>
    <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>

創(chuàng)建【poll_vote.php】腳本文件

<?php 
  // 接收參數(shù)q
  $vote = htmlspecialchars($_REQUEST['q']);
  // 獲取文件中存儲的數(shù)據(jù)(這里需要在同一目錄下新建一個poll_result.txt文件)
  $filename = "poll_result.txt";
  $conn = file($filename);
  // 將數(shù)據(jù)分割到數(shù)組
  $array = explode("||", $conn[0]);
  $yes = $array[0];
  $no = $array[1];
  $count = $array[2];
  if ($vote == 0) {
    $yes += 1;
    $count += 1;
  }
  if ($vote == 1) {
    $no += 1;
    $count += 1;
  }
  // 將投票數(shù)據(jù)保存到文檔
  $insertvote = $yes . '||' . $no . '||' . $count;
  $fp = fopen($filename, "w");
  fputs($fp, $insertvote);
  fclose($fp);
 ?>
 <h3>結果:</h3>
 <table>
  <tr>
    <td>是:</td>
    <td>
      <span ></span><?php echo 100 * round($yes / ($yes + $no), 2); ?>%
    </td>
  </tr>
  <tr>
    <td>否:</td>
    <td>
      <span ></span><?php echo 100 * round($no / ($yes + $no), 2); ?>%
    </td>
  </tr>
 </table>
 <p><?php echo "參與人數(shù):" . $count; ?></p>

新建一個空白的文檔 【poll_result.txt】

此時目錄:

|-AJAX投票.html
|-poll_vote.php
|-poll_result.txt

如果不同則需修改上面相應的代碼

效果:

PHP+AJAX如何實現(xiàn)投票器功能
PHP+AJAX如何實現(xiàn)投票器功能

以上是“PHP+AJAX如何實現(xiàn)投票器功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI