在我的项目中,可以对帖子进行投票。当我不使用 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/