javascript 实现投票数据统计示例
前台代码:
1 <html> 2 <head> 3 <meta charset="utf-8"> 4 <title>投票数据统计(runoob.com)</title> 5 <script> 6 function getVote(int) { 7 if (window.XMLHttpRequest) { 8 // IE7+, Firefox, Chrome, Opera, Safari 执行代码 9 xmlhttp=new XMLHttpRequest(); 10 } else { 11 // IE6, IE5 执行代码 12 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 13 } 14 xmlhttp.onreadystatechange=function() { 15 if (xmlhttp.readyState==4 && xmlhttp.status==200) 16 { 17 document.getElementById("poll").innerHTML=xmlhttp.responseText; 18 } 19 } 20 xmlhttp.open("GET","http://localhost/test/ajax/poll_vote.php?vote="+int,true); 21 xmlhttp.send(); 22 } 23 </script> 24 </head> 25 <body> 26 27 <div id="poll"> 28 <h3>你喜欢 PHP 和 AJAX 吗?</h3> 29 <form> 30 是: 31 <input type="radio" name="vote" value="0" onclick="getVote(this.value)"> 32 <br>否: 33 <input type="radio" name="vote" value="1" onclick="getVote(this.value)"> 34 </form> 35 </div> 36 37 </body> 38 </html>
后台处理代码:
1 <?php 2 $vote = htmlspecialchars($_REQUEST['vote']); 3 4 // 获取文件中存储的数据 5 $filename = "poll_result.txt"; 6 $content = file($filename); 7 8 // 将数据分割到数组中 9 $array = explode("||", $content[0]); 10 $yes = $array[0]; 11 $no = $array[1]; 12 13 if ($vote == 0) 14 { 15 $yes = $yes + 1; 16 } 17 18 if ($vote == 1) 19 { 20 $no = $no + 1; 21 } 22 23 // 插入投票数据 24 $insertvote = $yes."||".$no; 25 $fp = fopen($filename,"w"); 26 fputs($fp,$insertvote); 27 fclose($fp); 28 ?> 29 30 <h2>结果:</h2> 31 <table> 32 <tr> 33 <td>是:</td> 34 <td> 35 <span style="display: inline-block; background-color:green; 36 width:<?php echo(100*round($yes/($no+$yes),2)); ?>px; 37 height:20px;" ></span> 38 <?php echo(100*round($yes/($no+$yes),2)); ?>% 39 </td> 40 </tr> 41 <tr> 42 <td>否:</td> 43 <td> 44 <span style="display: inline-block; background-color:red; 45 width:<?php echo(100*round($no/($no+$yes),2)); ?>px; 46 height:20px;"></span> 47 <?php echo(100*round($no/($no+$yes),2)); ?>% 48 </td> 49 </tr> 50 </table>