好的,所以我想使用Ajax向我的网站(基于django)添加投票。我在一个页面中有多个条目,但是现在我的代码只允许用户对第一个条目进行投票。请使用代码帮助我,以便用户可以对所有代码进行投票。
首先是html代码,基本上它只是供用户投票的投票按钮
{% for answer in answers %}<!-- django template -->
<strong id="vote_count">{{ answer.votes }}</strong> people vote this answer
{% if user.is_authenticated %}
<button id="vote" data-answerid="{{answer.id}}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Vote
</button>
{% endif %}
{% endfor %}<!-- end django template -->
其次,下面是处理请求的django视图
@login_required
def vote_answer(request):
answer_id = None
if request.method == 'GET':
answer_id = request.GET['answer_id']
votes = 0
if answer_id:
answer = Answer.objects.get(id=answer_id)
if answer:
votes = answer.votes + 1
answer.votes = votes
answer.save()
return HttpResponse(votes)
以下是网址映射:
url(r'^like_category/$', views.like_category, name='like_category'),
最后是javascript
$('#vote').click(function(){
var answerid;
answerid = $(this).attr("data-answerid");
$.get('/vote_answer/', {answer_id: answerid}, function(data){
$('#vote_count').html(data);
$('#vote').hide();
});
});
同样,我的问题是我在一页中拥有的所有条目,使用此代码,我只能对第一个进行投票。如何修改它,以便我可以全部投票
您需要使用class
而不是id
on <button>
,以便多个按钮可以共享相同的jQuery事件处理程序。
<button class="vote" data-answerid="...">
然后,您可以在JavaScript中执行以下操作:
$(document).on("click", ".vote", function(){
var answerid;
answerid = $(this).attr("data-answerid");
$.get('/vote_answer/', {answer_id: answerid}, function(data){
$('#vote_count').html(data);
$('#vote').hide();
});
});
这将绑定事件处理程序以单击any <button class=vote>
。
同样,您应该执行AJAX POST而不是HTTP语义的GET,因为投票是一种状态更改操作。否则,浏览器或Web代理可能会缓存结果(尽管jQuery有其自己的缓存破坏器)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句