1. 程式人生 > >PHP - AJAX投票

PHP - AJAX投票

int input 字符轉換 .get col ron ref safari request

上代碼…
兩個文件:poll.html poll_vote.php
poll.html:

<html>
<head>
<meta charset="utf-8">
<title>ajax投票</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","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>

  

poll_vote.php:

<?php
$vote = htmlspecialchars($_REQUEST[‘vote‘]);   //把預定義的字符轉換為 HTML 實體

// 獲取文件中存儲的數據
$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>

  

PHP - AJAX投票