2016-11-08 179 views
0

我正在做一个投票系统与jQuery AJAX。当点击div(投票时)时,数据被发送到中间文件(在这种情况下为up_vote.php),然后div用新数据更新。它完美地工作,给出结果= 2(变量加一)。投票系统与jQuery AJAX

在第二阶段,我尝试在另一个div(#results在页面的另一个站点)中显示投票结果。问题是,它会刷新div,但结果不正确,显示1而不是2(看起来像变量没有被发送,或者div在接收结果之前刷新)。

我离开的情况下,任何人想尝试的完整代码...

的Index.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没有显示正确的结果?会发生什么,我该如何解决它?

回答

2

而不是使用$("#results").load("up_vote.php");加载up_vote.php(obviousely传递$ id_field不设空,因为您加载通过get和不带参数的URL),因此它正常的,你有,而不是1 2
你有使用相同的成功html从服务器返回,以显示它在第二个div,如$("#results").html(html);