jquery - 我的 Jquery-Ajax 投票代码遇到问题

标签 jquery python html ajax django

在我的项目中,可以对帖子进行投票。当我不使用 Jquery-Ajax 时,这工作得很好。不过,它会重新加载页面,但我不希望这样。

我实现了一些 Jquery-Ajax 来执行 POST 请求,并更新按钮以表示已投票。不幸的是,这会导致列表中的所有帖子都被投票,而不仅仅是我点击的帖子。

让我向您展示 HTML(在帖子列表 for 循环内):

{% for post in posts %}
{{ post.title }}
<hr>
{{ post.content }}
{% with user=request.user %}
    <a class="upvote" data-postid="{{ post.id }}"  href='#' >
        <span class="btn btn-primary" aria-hidden="true">
            Upvote | {{ post.followers }}
        </span>
    </a>

        {% endwith %}
        {% endfor {%

这是赞成票和已投票按钮的 HTML。

这是我的 Jquery 脚本:

<script src="{% static 'posts/jquery-3.1.1.js' %}"></script>

<script type="text/javascript">
$(".upvote").click(function(event){
var postid = $(this).data('postid');
$.ajax({url: "/activity/follow/10/{{ post.id }}?next={{ request.path }}&postid=" + postid, success: function (data) {
     event.preventDefault();

    $(".upvote").addClass('hidden');

    }


});

});
    </script>

总而言之,如何让此函数仅对我点击的帖子进行投票,而不是对列表中的每个帖子进行投票?谢谢!

最佳答案

您需要将 postid 变量放入 Controller URL,而不是 {{post.id}}。 Javascript 代码不应位于循环中,因此它无权访问 post 变量。

$(".upvote").click(function(event){
    event.preventDefault();
    var postid = $(this).data('postid');
    var $this = $(this);
    $.ajax({
        url: "/activity/follow/10/" + postid + "?next={{ request.path }}", 
        success: function (data) {
            $this.addClass('hidden');
        }
    });
});

关于jquery - 我的 Jquery-Ajax 投票代码遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41274141/

相关文章:

python - 如何在 sqlalchemy 声明中设置属性默认值?

python - PIL 图像到数组(numpy 数组到数组) - Python

系谱的 HTML CSS 无序列表。如何让它在IE8中显示与firefox保持一致?

javascript - 验证只有 5 个值的文本字段

javascript - 基本的 jQuery 问题

c# - ASP.NET 验证不工作

python - 如何使用 pyqt5 在模型/ View qml 中查看我的数据

html - 我想用css来控制视频标签的宽度和高度

javascript - 日期选择器出现问题 : Missing instance data

jquery。单击 div,获取 div 的 id 并将该 id 用作 jquery .css ("background-image"的一部分