如何在Django中响应ajax请求

9

我有这样的代码:

$(document).ready(function(){
    $('#error').hide();
    $('#submit').click(function(){
        var name = $("#name").val();
        if (name == "") {
            $("#error").show("slow");
            return false;
        }
        var pass = $("#password").val();
        if (pass == "") {
            $("#error").show("slow");
            return false;
        }
        $.ajax({
            url: "/ajax/",
            type: "POST",
            data: name,
            cache:false,
            success: function(resp){
                alert ("resp");
            }
        });
    });
});

在Django中查看:

def lat_ajax(request):
    if request.POST and request.is_ajax:
        name = request.POST.get('name')
        return HttpResponse(name)
    else :
        return render_to_response('ajax_test.html',locals())

我的哪里错了?我是Django的初学者,请帮帮我。


3
什么是错误信息?行为表现是什么?你能发布你的url.py吗? - Skyrel
CSRF令牌?出了什么错误? - Jurudocs
不是 "request.is_ajax",你需要调用它为 "request.is_ajax()"。 - id614515
6个回答

20

在jquery调用中加入dataType: "json"。 响应将是一个javascript对象。

$.ajax({
    url: "/ajax/",
    type: "POST",
    data: name,
    cache:false,
    dataType: "json",
    success: function(resp){
        alert ("resp: "+resp.name);
    }
});
在Django中,您必须返回一个json序列化的字典包含数据。content_type必须是application/json。在这种情况下,不建议使用locals技巧,因为有些局部变量可能无法在json中序列化。这将引发异常。还请注意is_ajax是一个函数,必须调用它。在您的情况下它将始终为真。我还会测试request.method而不是request.POST
import json
def lat_ajax(request):

    if request.method == 'POST' and request.is_ajax():
        name = request.POST.get('name')
        return HttpResponse(json.dumps({'name': name}), content_type="application/json")
    else :
        return render_to_response('ajax_test.html', locals())

更新:正如Jurudocs所提到的,csrf_token也可能是一个原因。我建议阅读:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax


10

如何创建字典并转换为JSON格式:

name = request.POST.get('name')
dict = {'name':name}
return HttpResponse(json.dumps(dict), content_type='application/json')

我的代码仍然无法运行,Django 没有响应。你能告诉我参考学习资料吗? - CitooZz Banditozz
有很多教程:http://webcloud.se/log/AJAX-in-Django-with-jQuery/http://brack3t.com/ajax-and-django-views.htmlhttp://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/ - Lukasz Koziara

2

您有一个拼写错误:

    success: function(resp){
        alert ("resp");
    }

应该是

        success: function(resp){
            alert (resp);
        }

此外,关于csrf,你必须使用以下方式的头部信息:
    $.ajax({
            url: "some-url",
            headers: {'X-CSRFToken': '{{ csrf_token }}'},

1
只需这样做...(Django 1.11)
from django.http.response import JsonResponse

return JsonResponse({'success':False, 'errorMsg':errorMsg})

当你在jQuery中处理json部分时,请执行以下操作:

$.ajax({
    ...
    dataType: 'json',
    success: function(returned, status, xhr) {
        var result = returned['success']; // this will be translated into 'true' in JS, not 'True' as string
        if (result) { 
            ...
        else {
            ...
        }
    }
});

0

如果什么都不起作用,就在你的函数前面加上"@csrf_exempt"

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def lat_ajax(request):
"""
your code
"""

0
$(document).ready(function(){
    $('#error').hide();
    $('#submit').click(function(){
        var name = $("#name").val();
        if (name == "") {
            $("#error").show("slow");
            return false;
        }
        var pass = $("#password").val();
        if (pass == "") {
            $("#error").show("slow");
            return false;
        }
        $.ajax({
            url: "/ajax/",
            type: "POST",
            data: { 
                'name': name, 
                'csrfmiddlewaretoken': '{{csrf_token}}'
            }, 
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function(data) { 
                alert(data);
            },
            error: function(ts) { 
                alert(ts);
            }
        });
    });
});


def lat_ajax(request):
    if request.POST:
        name = request.POST['name']
        return HttpResponse(name)
    else :
        return render_to_response('ajax_test.html',locals())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接