我正在研究jQuery教程(链接),但一直停留在"RATE ME:使用AJAX"部分
jQuery的:
$(document).ready(function() { // generate markup $("#rating").append("Please rate: "); for ( var i = 1; i <= 5; i++ ) $("#rating").append("" + i + " "); // add markup to container and apply click handlers to anchors $("#rating a").click(function(e){ // stop normal link click e.preventDefault(); // send request $.post("/vote", {rating: $(this).html()}, function(xml) { // format and output result $("#rating div").html( "Thanks for rating, current average: " + $("average", xml).text() + ", number of votes: " + $("count", xml).text() ); }); }); });
urls.py:
urlpatterns = patterns('', (r'^rating/$', 'ajax_rating.views.rating'), (r'^vote/$', 'ajax_rating.views.vote'), )
views.py:
@csrf_exempt def vote(request): if request.is_ajax(): rating = request['rating'] f = open('ratings.dat', 'w') votes = json.load(f) votes.append(rating) f.close() dict = {} total_rating = sum(votes) dict['count'] = len(votes) dict['avg'] = total_rating / dict['count'] return HttpResponse(serializers.serialize('xml', dict), 'application/xml') else: return HttpResponse(status=400)
基本上,html为用户提供了1到5之间的选择(具有class = rating的锚点).单击选项后,将使用从服务器返回的计算结果刷新#rating div.
问题:当我点击某个选项时,我收到"HTTP 500内部服务器错误".甚至在请求命中视图函数,投票(请求)之前就会发生错误.我试图找出错误的原因,但没有任何线索.我不认为它与csrf有任何关系,因为我在视图函数上使用@csrf_exempt并从MIDDLEWARE_CLASSES中取出'django.middleware.csrf.CsrfViewMiddleware'.
请帮忙~~感谢您的专家
我相信POST应该转到URL /vote/
而不仅仅是/vote
.
rating
不会是一个有效的密钥request
.你可能正在寻找request.POST['rating']
.或者,为了安全起见,您不要抛出更多关键错误:
rating = request.POST.get('rating', None) if rating is None: return HttpResponse(status=400) ## or some error.