【问题标题】:Voting system with jQuery AJAX使用 jQuery AJAX 的投票系统
【发布时间】: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 没有显示正确的结果吗?会发生什么,我该如何解决?

【问题讨论】:

    标签: jquery vote


    【解决方案1】:

    而不是使用 $("#results").load("up_vote.php"); 加载 up_vote.php (显然传递 $id_field 为未设置和空,因为您通过 get 加载 url 并且没有参数)所以您得到 1 而不是 2 是正常的。
    您必须使用从服务器返回的相同成功 html 才能在第二个 div 中显示它,例如 $("#results").html(html);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多