【发布时间】:2017-03-22 05:39:34
【问题描述】:
我正在使用 jQuery AJAX 做一个投票系统。当点击div(投票时)时,数据被发送到一个中间文件(在本例中为up_vote.php),然后用新数据更新div。它完美地工作,给出结果 = 2(变量加一)。
在第二阶段,我尝试在另一个 div 中显示投票结果(页面的另一个站点中的#results)。问题是,它刷新了div,但结果不正确,显示的是1而不是2(看起来变量没有发送,或者div在收到结果之前就刷新了)。
我留下完整的代码,以防有人想尝试......
索引.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link type="text/css" rel="stylesheet" href="style.css" />
<script type="text/javascript" src="myjquery.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$(".n_vote").click(function() {
var id_field = $(this).attr("id");
var parent = $(this);
$.ajax({
type: "POST",
url: "up_vote.php",
data: {
id_field: id_field,
name: name
},
cache: false,
success: function(html) {
//Show the results in the same div
parent.html(html);
//Show the results in another div, #results
$("#results").load("up_vote.php");
}
});
return false;
});
});
</script>
<div class="vote_system">
<div class="n_vote" name="up" id="1">Clic here to show the result</div>
</div>
<!-- Correct result=2 -->
______________________________
<br>
Show the result in a another div:
<br>
<div class="results" id="results">
</div>
<!-- Incorrect result=1 -->
</body>
</html>
up_vote.php
<?php
$id_field = $_POST['id_field'];
echo 'Result=';
echo $id_field + 1;
?>
有更多经验的人可以向我解释为什么第二个 div 没有显示正确的结果吗?会发生什么,我该如何解决?
【问题讨论】: