查看投票结果而不影响结果

时间:2014-05-30 02:49:55

标签: javascript php onclick href

我有以下代码进行投票。

<html>
<head>
<script>
function getVote(int) {
  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.php?vote="+int,true);
  xmlhttp.send();
}
</script>
</head>

<body>
<div id="poll">
<h3>First Question?</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> 

结果出现在这个PHP文件(poll_vote.php)中:

<?php
$vote = $_REQUEST['vote'];

$filename = "poll_result.txt";
$content = file($filename);

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

if ($vote == 0) {
  $yes = $yes + 1;
}
if ($vote == 1) {
  $no = $no + 1;
}

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

我想添加一个“查看结果”链接(不影响投票结果)。我使用了以下代码,它实际上显示了结果,但由于某些原因,它为投票的第一个选项增加了一票:

<a onclick="getVote(this.value)" href="#poll">View Results</a>

任何建议都不仅仅是值得赞赏的。

谢谢!

1 个答案:

答案 0 :(得分:0)

由于您使用相同的代码来更新和查看结果,因此您需要一种绕过更新的方法。

我会用:

<a onclick="getVote(-1)" href="#poll">View Results</a>

在php中:

if( $vote != -1 ) {
  if ($vote == 0) {
    $yes = $yes + 1;
  }
  if ($vote == 1) {
    $no = $no + 1;
  }

  $insertvote = $yes."||".$no;
  $fp = fopen($filename,"w");
  fputs($fp,$insertvote);
  fclose($fp);
}
相关问题