问题
如何制作一个Ajax按钮(向上和向下箭头),使得数字可以增加或减少
如何将用户的动作保存到变量NumberOfVotesOfQuestionID
我不确定是否应该使用数据库或不使用数据库.但是,我知道有一种更简单的方法可以节省投票数.
你怎么解决这些问题?
[编辑]
服务器端编程语言是Python.
这是一个使用jQuery/Django的脏/未经测试的理论实现.
我们将假设上下投票是针对本网站上的问题/答案,但显然可以根据您的实际用例进行调整.
0Blah blah blah this is my answer.0Blah blah blah this is my other answer.
$(function() { $('div.answer img.vote').click(function() { var id = $(this).parents('div.answer').attr('id').split('_')[1]; var vote_type = $(this).hasClass('up') ? 'up' : 'down'; if($(this).hasClass('selected')) { $.post('/vote/', {id: id, type: vote_type}, function(json) { if(json.success == 'success') { $('#answer_' + id) .find('img.' + vote_type); .attr('src', 'vote_' + vote_type + '_selected.png') .addClass('selected'); $('div.score', '#answer_' + id).html(json.score); } }); } else { $.post('/remove_vote/', {id: id, type: vote_type}, function(json) { if(json.success == 'success') { $('#answer_' + id) .find('img.' + vote_type); .attr('src', 'vote_' + vote_type + '.png') .removeClass('selected'); $('div.score', '#answer_' + id).html(json.score); } }); } }); });
def vote(request): if request.method == 'POST': try: answer = Answer.objects.get(pk=request.POST['id']) except Answer.DoesNotExist: return HttpResponse("{'success': 'false'}") try: vote = Vote.objects.get(answer=answer, user=request.user) except Vote.DoesNotExist: pass else: return HttpResponse("{'success': 'false'}") if request.POST['type'] == 'up': answer.score = answer.score + 1 else: answer.score = answer.score - 1 answer.save() Vote.objects.create(answer=answer, user=request.user, type=request.POST['type']) return HttpResponse("{'success':'true', 'score':" + answer.score + "}") else: raise Http404('What are you doing here?') def remove_vote(request): if request.method == 'POST': try: answer = Answer.objects.get(pk=request.POST['id']) except Answer.DoesNotExist: return HttpResponse("{'success': 'false'}") try: vote = Vote.objects.get(answer=answer, user=request.user) except Vote.DoesNotExist: return HttpResponse("{'success': 'false'}") else: vote.delete() if request.POST['type'] == 'up': answer.score = answer.score - 1 else: answer.score = answer.score + 1 answer.save() return HttpResponse("{'success':'true', 'score':" + answer.score + "}") else: raise Http404('What are you doing here?')
让人惊讶.当我开始回答这个问题时,我并不打算写这么多,但我得到了一点点.您仍然缺少初次请求以在首次加载页面时获得所有投票,但我会将其作为练习留给读者.总之,如果你是实际上是使用Django和感兴趣的投票#1的测试更加/实FPGA实现,我建议你检查出的源代码为cnprog.com,用Python编写/ Django的#1的中国克隆.他们发布了他们的代码并且相当不错.
没有人提到过几点:
更改数据库的状态时,您不希望使用GET.否则我可以在我的网站上放一张图片src="http://stackoverflow.com/question_555/vote/up/answer_3/"
.
您还需要csrf(跨站点请求伪造)保护
您必须记录每次投票的人,以避免人们针对特定问题多次投票.无论是IP地址还是用户ID.