Skip to main content
 首页 » 编程设计

jquery之Django 。 ajax调用后数字不会增加

2024年10月25日36sky-heaven

我正在重写这个问题,因为我不确定如果发布一个新问题是否会产生重复问题。第一条评论是对原始问题的回答。

我有一个考试项目,部分是为了编写一个带有注释的 Django 站点,登录用户可以在其中对注释进行投票。

html 代码、url、 View 和 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)) 

请您参考如下方法:

你的问题出在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 解析:

网址.py

url(r'^(P<id>[\d\w]+)/increase_num_likes/$', increase_num_likes, name='increase_numlikes') 

View .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> 

此外,设置正确的 header 也很重要:

documentation建议您在使用 AJAX 发布数据时需要设置 X-CSRFToken header ,该数据不是包含 {% csrftoken %} 标记的表单。

使用 jquery 在客户端获取 token 很简单:

var csrftoken = $.cookie('csrftoken'); 

在您的 ajax 调用中设置正确的 header :

$.ajax({ 
      method: "POST", 
      headers: { 'X-CSRFToken': $.cookie('csrftoken') } 
      url: $('#num_likes_url').val() 
    }) 

我怀疑您的 POST 从未到达您的 View 并被 CSRFProtectionMiddleware 捕获