我不确定为什么会收到此错误。我有最喜欢的应用程序,而ajax必须分崩离析。因为当我单击一个应该工作但现在不工作的按钮时会发生此错误。我的猜测是我;我错过了一些csrf或cookie或错误的jquery版本....我不确定。这是我的代码
和html文件
<div class="actions">{% if user.is_authenticated %}{% fav_item category user %}{% endif %}</div>
</div>
我也会发布views.py
def ajax_login_required(view_func):
def wrap(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
json = simplejson.dumps({'not_authenticated': True})
return HttpResponse(json, content_type='application/json', status=401)
wrap.__doc__ = view_func.__doc__
wrap.__dict__ = view_func.__dict__
return wrap
@ajax_login_required
def ajax_fav(request, ctype_id, obj_id):
"""
"""
ctype = get_object_or_404(ContentType, pk=ctype_id)
item = ctype.get_object_for_this_type(pk=obj_id)
if Favorite.objects.filter(user=request.user, content_type=ctype, object_id=obj_id):
fav = Favorite.objects.get(user=request.user, content_type=ctype, object_id=obj_id)
fav.delete()
count = Favorite.objects.favorites_for_object(item).count()
data_dict = {'id': 0, 'message': fav_settings.FAV_ADD, 'counter': build_message(count), }
else:
fav = Favorite.objects.create_favorite(item, request.user)
count = Favorite.objects.favorites_for_object(item).count()
data_dict = {'id': fav.id, 'message': fav_settings.FAV_REMOVE, 'counter': build_message(count), }
return HttpResponse(simplejson.dumps(data_dict), content_type='application/javascript')
编辑:/在控制台中我得到js错误 未捕获的SyntaxError:意外的标识符
$(function(){
$('a.favIt').on('click', function(){
var itemId = $(this).attr('id').split("_")[1];
$.ajax({
type: "POST",
url: $(this).attr("href"),
data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
dataType: "json",
timeout: 2000,
cache: false,
beforeSend: function(XMLHttpRequest) {
//$("#loader").fadeIn();
},
error: function(data, XMLHttpRequest, textStatus, errorThrown){
$(this).html("Error connecting to the server.");
},
complete: function(XMLHttpRequest, textStatus) {
//$("#loader").fadeOut();
},
success: function(data, textStatus, XMLHttpRequest){
$('#FavIt_'+itemId).html(data.message);
$('#FavCounter_'+itemId).html(data.counter);
}
});
return false;
});
});
它说它出现在第8行,即dataType:“json”,我发布了views.py
答案 0 :(得分:1)
您需要将csrf标记作为ajax调用中数据的一部分传递:
data: {csrfmiddlewaretoken: '{{ csrf_token }}'}