PHP 实例 - AJAX 投票
AJAX 投票
下例将演示如何在不重新加载页面的情况下显示投票结果。
到目前为止,你喜欢 PHP 和 AJAX 吗?
实例解释 - HTML 页面
当用户选择上面的选项时,会执行名为 getVote() 的函数。该函数由 onclick 事件触发:
<html>
<head>
<script>
function getVote(int) {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("poll").innerHTML=this.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() 函数执行以下操作:
- 创建一个
XMLHttpRequest对象 - 创建服务器响应就绪时要执行的函数
- 将请求发送到服务器上的文件
- 请注意,参数(
vote)已添加到 URL(带有是或否选项的值)
PHP 文件
上面 JavaScript 调用的服务器上的页面是一个名为 "poll_vote.php" 的 PHP 文件:
<?php
$vote = $_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><img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>否:</td>
<td><img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
该值从 JavaScript 发送,然后发生以下情况:
- 获取 "poll_result.txt" 文件的内容
- 将文件内容放入变量中,并为所选变量加一
- 将结果写入 "poll_result.txt" 文件
- 输出投票结果的图形表示
文本文件
文本文件(poll_result.txt)是我们存储投票数据的地方。
它的存储方式如下:
0||0
第一个数字代表“是”投票数,第二个数字代表“否”投票数。
注意:请记得允许您的 Web 服务器编辑文本文件。不要给所有人访问权限,只给 Web 服务器(PHP)访问权限。