终于到ajax,翻译过来就是”异步javascript和xml”,他可以实现网页内容的部分加载,可提高用户体验。现在有很多网站都有用这技术,反正你知道他能实现网页的异步更新就差不多了。当然下面的例子都相对简单,并没有体现它这一特点~
投票器
新建文件【 ajax投票.html】
<html>
<head>
<script type="text/javascript">
// 这里是js代码
function getvote(int) {
if (window.xmlhttprequest) {
// 创建 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) {
// 找到 id 为 poll 的控件
document.getelementbyid('poll').innerhtml = xmlhttp.responsetext;
}
}
// 向php脚本传递主要参数q
xmlhttp.open("get", "poll_vote.php?q=" + int, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>你喜欢吃吗?</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
// 接收参数q
$vote = htmlspecialchars($_request['q']);
// 获取文件中存储的数据(这里需要在同一目录下新建一个poll_result.txt文件)
$filename = "poll_result.txt";
$conn = file($filename);
// 将数据分割到数组
$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;
}
// 将投票数据保存到文档
$insertvote = $yes . '||' . $no . '||' . $count;
$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 / ($yes + $no), 2);?>px; height: 20px;"></span><?php echo 100 * round($yes / ($yes + $no), 2); ?>%
</td>
</tr>
<tr>
<td>否:</td>
<td>
<span style="display: inline-block; background-color: red; width: <?php echo 100 * round($no / ($yes + $no), 2);?>px; height: 20px;"></span><?php echo 100 * round($no / ($yes + $no), 2); ?>%
</td>
</tr>
</table>
<p><?php echo "参与人数:" . $count; ?></p>
新建一个空白的文档 【poll_result.txt】
此时目录:
|-ajax投票.html
|-poll_vote.php
|-poll_result.txt
如果不同则需修改上面相应的代码
效果:
总结
以上所述是小编给大家介绍的php+ajax 投票器功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!