本文实例讲述了php+ajax实现投票功能的方法。分享给大家供大家参考。具体如下:
在这个 ajax 实例中,我们将演示一个投票程序,网页在不重新加载的情况下,就可以获得结果。
本例包括四个元素:
① html 表单
② javascript
③ php 页面
④ 存放结果的文本文件
一、html 表单
这是 html 页面。它包含一个简单的 html 表单,以及一个与 javascript 文件的连接:
<html> <head> <script src="poll.js"></script> </head> <body> <div id="poll"> <h2>do you like php and ajax so far?</h2> <form> yes: <input type="radio" name="vote" value="0" onclick="getvote(this.value)"> <br /> no: <input type="radio" name="vote" value="1" onclick="getvote(this.value)"> </form> </div> </body> </html>
例子解释 - html 表单
正如您看到的,上面的 html 页面包含一个简单的 html 表单,其中的 <div> 元素带有两个单选按钮。
表单这样工作:
1. 当用户选择 "yes" 或 "no" 时,会触发一个事件
2. 当事件触发时,执行 getvote() 函数
3. 围绕该表单的是名为 "poll" 的 <div>。当数据从 getvote() 函数返回时,返回的数据会替代该表单。
二、文本文件
文本文件 (poll_result.txt) 中存储来自投票程序的数据。
它类似这样:
0||0
第一个数字表示 "yes" 投票,第二个数字表示 "no" 投票。
注释:记得只允许您的 web 服务器来编辑该文本文件。不要让其他人获得访问权,除了 web 服务器 (php)。
三、javascript
javascript 代码存储在 "poll.js" 中,并于 html 文档相连接:
var xmlhttp
function getvote(int)
{
xmlhttp=getxmlhttpobject()
if (xmlhttp==null)
{
alert ("browser does not support http request")
return
}
var url="poll_vote.php"
url=url+"?vote="+int
url=url+"&sid="+math.random()
xmlhttp.onreadystatechange=statechanged
xmlhttp.open("get",url,true)
xmlhttp.send(null)
}
function statechanged()
{
if (xmlhttp.readystate==4 || xmlhttp.readystate=="complete")
{
document.getelementbyid("poll").
innerhtml=xmlhttp.responsetext;
}
}
function getxmlhttpobject()
{
var objxmlhttp=null
if (window.xmlhttprequest)
{
objxmlhttp=new xmlhttprequest()
}
else if (window.activexobject)
{
objxmlhttp=new activexobject("microsoft.xmlhttp")
}
return objxmlhttp
}
例子解释:
statechanged() 和 getxmlhttpobject 函数与 php 和 ajax 请求 这一节中的例子相同。
getvote() 函数
当用户在 html 表单中选择 "yes" 或 "no" 时,该函数就会执行。
1. 定义发送到服务器的 url (文件名)
2. 向 url 添加参数 (vote),参数中带有输入字段的内容
3. 添加一个随机数,以防止服务器使用缓存的文件
4. 调用 getxmlhttpobject 函数来创建 xmlhttp 对象,并告知该对象当触发一个变化时执行 statechanged 函数
5. 用给定的 url 来打开 xmlhttp 对象
6. 向服务器发送 http 请求
四、php页面
由 javascript 代码调用的服务器页面是名为 "poll_vote.php" 的一个简单的 php 文件。
<?php
$vote = $_request['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0)
{
$yes = $yes + 1;
}
if ($vote == 1)
{
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>result:</h2>
<table>
<tr>
<td>yes:</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>no:</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 传来,然后会发生:
1. 获取 "poll_result.txt" 文件的内容
2. 把文件内容放入变量,并向被选变量累加 1
3. 把结果写入 "poll_result.txt" 文件
4. 输出图形化的投票结果
希望本文所述对大家的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!