21xrx.com
2024-03-19 19:55:46 Tuesday
登录
文章检索 我的文章 写文章
PHP示例 - AJAX轮询
2021-08-01 11:24:12 深夜i     --     --
PHP示例 -  Ajax民意调查


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>Do you like PHP and AJAX so far?</h3>
<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>

getVote()函数执行以下操作:

  • 创建XMLHTTPRequest对象
  • 创建服务器响应已准备就绪时要执行的函数
  • 将请求发送到服务器上的文件
  • 请注意,参数(poll)将添加到URL(“1”或“0”的值)


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. 将文件内容放入变量中,并在选中的变量中加一
  3. 将结果写入“poll_result.txt”文件
  4. 输出投票结果

 

  
  
下一篇: PHP数组函数

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章