我正在重写这个问题,因为我不确定如果发布一个新的,我是否会产生重复。第一条评论是对原始问题的回答。
我有一个考试项目,部分是写一个Django网站,注释用户可以在笔记上投票。
html代码,网址,视图和jQuery不会出现任何错误。但是,点击Bootstrap中的竖起大拇指图标后,喜欢的数量不会增加。
更新了Liαrεz和Sebastian Wozny的建议
有人可以帮助我吗?
JS档案
$(document).ready(function(){
var csrftoken = $.cookie('csrftoken');
$("#increase_num_likes_thumb").click(function(event){
event.preventDefault();
$.ajax({
method: "POST",
headers: { 'X-CSRFToken': $.cookie('csrftoken') },
url: $('#num_likes_url').val(),
success: function(data){
result = JSON.parse(data);
if (result.error){
consloe.log(result.error_text);
}else{
var num_likes_updated = result['num_likes_updated'];
$("#num_likes_div").html(num_likes_updated);
}
}
});
});
});
HTML
<div class="row">
<div class="col-sm-10">
{% if notes %}
{% for note in notes %}
<div class="col-sm-5" style="border: 1px solid; margin: 10px;">
<h3 class="page-header"><a href="{% url 'notes:detailnote' %}?id={{ note.id }}">{{ note.label }}</a></h3>
<div style="padding: 5px;">
{{ note.body }}
<p>
<div>
<a href="/notes/?id={{ note.id }}/increase_num_likes/" id="increase_num_likes_thumb">
<span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span>
</a>
</div>
<div id="num_likes_div">
{{ note.num_likes }}
</div>
</p>
<input type="hidden" id="num_likes_url" value="/notes/increase_num_likes/?id={{ note.id }}" >
</div>
</div>
{% endfor %}
{% endif %}
</div>
</div>
urls.py
from django.conf.urls import patterns
from django.conf.urls import url
from django.conf.urls import include
from notes.views import increase_num_likes
urlpatterns = patterns('',
url(r'^(P<id>[\d\w]+)/increase_num_likes/$',
increase_num_likes, name='increase_numlikes'),
,
Views.py
import json
from django.http import HttpResponse
def increase_num_likes(request):
id = request.GET.get('id', None)
if id is None:
note = get_object_or_404(Note, id=id)
data = {'error': True, 'error_text': 'Not ID supplied'}
else:
note = Note.objects.get(id=int(id))
note.num_likes += 1
note.save()
data = {'num_likes_updated': note.num_likes}
return HttpResponse(simplejson.dumps(data))
答案 0 :(得分:1)
您应该将AJAX视图更改为:
from django.http import HttpResponse
import json
def increase_num_likes(request):
id = request.GET.get('id', None)
if id is None:
note = get_object_or_404(Note, id=id)
data = {'error':True, 'error_text': 'Not ID supplied'}
else:
note = Note.objects.get(id=int(id))
note.num_likes += 1
note.save()
data = {'num_likes_updated': note.num_likes}
return HttpResponse(simplejson.dumps(data))
并将您的AJAX .done更改为.success管理错误:
$(document).ready(function(){
$("#increase_num_likes_thumb").click(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: $('#num_likes_url').val()
})
.success: function(data) {
result = JSON.parse(data); # Parse the data received
if (result.error){
console.log(result.error_text);
}else{
var num_likes_updated = result['num_likes_updated'];
$("#num_likes_div").html(num_likes_updated);
}
})
});
});
答案 1 :(得分:1)
您的问题在于url: $('#num_likes_url').val()
<input type="hidden" id="num_likes_url" value="/notes/?id={{ note.id }}/increase_num_likes/" >
所以value
是"/notes/?id={{ note.id }}/increase_num_likes/"
,它不是有效的URI。来自wikipedia:
<scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ]
如果你想将id作为get参数检索,那么正确的方法就是调用。
"/notes/increase_num_likes/?id={{ note.id }}"
你的urls.py
url(r'^increase_num_likes/$', increase_num_likes, name='increase_numlikes')
或者你可以使用djangos url解析:
urls.py
url(r'^(P<id>[\d\w]+)/increase_num_likes/$', increase_num_likes, name='increase_numlikes')
views.py
from import json
def increase_num_likes(request,id):
if id is None:
note = get_object_or_404(Note, id=id)
data = {'error': True, 'error_text': 'Not ID supplied'}
else:
note = Note.objects.get(id=int(id))
note.num_likes += 1
note.save()
data = {'num_likes_updated': note.num_likes}
return HttpResponse(simplejson.dumps(data))
<强> HTML 强>
<div class="row">
<div class="col-sm-10">
{% if notes %}
{% for note in notes %}
<div class="col-sm-5" style="border: 1px solid; margin: 10px;">
<h3 class="page-header"><a href="{% url 'notes:detailnote' %}?id={{ note.id }}">{{ note.label }}</a></h3>
<div style="padding: 5px;">
{{ note.body }}
<p>
<div>
<a href="/notes/?id={{ note.id }}/increase_num_likes/" id="increase_num_likes_thumb">
<span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span>
</a>
</div>
<div id="num_likes_div">
{{ note.num_likes }}
</div>
</p>
<input type="hidden" id="num_likes_url" value="/notes/increase_num_likes/?id={{ note.id }}" >
</div>
</div>
{% endfor %}
{% endif %}
</div>
</div>
此外,设置正确的标题非常重要:
documentation建议您在使用不是包含X-CSRFToken
标记的表单的AJAX发布数据时需要设置{% csrftoken %}
标题。
使用jquery获取客户端上的令牌非常简单:
var csrftoken = $.cookie('csrftoken');
在ajax调用上设置正确的标题:
$.ajax({
method: "POST",
headers: { 'X-CSRFToken': $.cookie('csrftoken') }
url: $('#num_likes_url').val()
})
我怀疑你的POST永远不会到达你的视线并被CSRFProtectionMiddleware
抓住