1. 当点击了投票后,利用 Ajax 刷新投票结果并把服务器返回的投票结果重新显示票数; (jQuery 来实现)。
2. 投票结果可以保存在数据库和文件中。
web实验9_2.php代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在线投票</title>
<style>
#main{
margin: auto;
}
#p{
width: 300px;
margin: auto;
}
</style>
<?php $con=file_get_contents("web_9_2data.txt");
$ar=explode(",",$con);?>
<script>
function load(name) {
var xhr = new XMLHttpRequest();
okStatus = document.location.protocol === "file:" ? 0 : 200;
xhr.open('GET', name, false);
xhr.overrideMimeType("text/html;charset=utf-8");
xhr.send(null);
return xhr.status === okStatus ? xhr.responseText : null;
}
function Ticket(id){
var xhr=new XMLHttpRequest();
xhr.onload=function (e) {
if (xhr.status==200){
let result=load("web_9_2data.txt");
var num=result.split(',');
document.getElementById('span0').innerHTML=num[0];
document.getElementById('span1').innerHTML=num[1];
document.getElementById('span2').innerHTML=num[2];
}
}
xhr.open("GET","web_实验9_2_1.php?id="+id,true);
xhr.send("id="+id);
console.log(id);
}
</script>
</head>
<body>
<div>
<div id="main">
<div id="p"><h2>我最喜欢的花卉评比</h2></div>
<table style="margin: auto">
<tr>
<td><img id="img0" src="../.idea/image/f2.jpg" height="200px" width="280px"></td>
<td><img id="img1" src="../.idea/image/f3.jpg" height="200px" width="280px"></td>
<td><img id="img2" src="../.idea/image/f4.jpg" height="200px" width="280px"></td>
</tr>
<tr>
<td><span id="span0">30</span>票</td>
<td><span id="span1">20</span>票</td>
<td><span id="span2">8</span>票</td>
</tr>
<tr>
<td><input type="button" value="投票" id="bt0" name="vote" onclick="Ticket(0);"></td>
<td><input type="button" value="投票" id="bt1" name="vote" onclick="Ticket(1);"></td>
<td><input type="button" value="投票" id="bt2" name="vote" onclick="Ticket(2);"></td>
</tr>
</table>
</div>
</div>
</body>
</html>
web_实验9_2_1.php代码:
<?php
$votefile="web_9_2data.txt";
$data=file_get_contents('web_9_2data.txt'); //连接文件
$id=$_GET['id'];
$votes=explode(",",$data);
if ($id==0)
$votes[0]++;
if($id==1)
$votes[1]++;
if ($id==2)
$votes[2]++;
$data=implode(",",$votes);
file_put_contents('web_9_2data.txt',$data);
?>
实验结果:
投票前后的投票的变化:
相关的数据只是简单保存在一个文件中