投票后在初始页面加载+上显示AJAX/PHP轮询结果

投票后在初始页面加载+上显示AJAX/PHP轮询结果,php,html,ajax,Php,Html,Ajax,使用w3school的PHP/AJAX民意测验示例,我很好奇如何修改它,以便在用户选择民意测验选项后,除了更新之外,还可以在初始页面加载时显示民意测验结果。包含代码的页面位于此处:。我还复制了以下内容: HTML文件: <html> <head> <script> function getVote(int) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Sa

使用w3school的PHP/AJAX民意测验示例,我很好奇如何修改它,以便在用户选择民意测验选项后,除了更新之外,还可以在初始页面加载时显示民意测验结果。包含代码的页面位于此处:。我还复制了以下内容:

HTML文件:

<html>

<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("poll").innerHTML=xmlhttp.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>
HTML编辑行:

<body onload="readVote();">
PHP新文件,名称为poll\u vote\u read.PHP:

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

?>

<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>
我认为这会起作用,但我没有测试它,如果它起作用就投票吧

<body onload="readVote();">
function readVote()
{
if (window.XMLHttpRequest)
  {
  xmlhttp = new XMLHttpRequest();
  }
else
  {
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange = function()
  {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
    document.getElementById("poll").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","poll_vote_read.php",true);
xmlhttp.send();
}
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

?>

<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>