如何在Django中响应ajax请求

时间:2013-02-01 08:14:28

标签: python django

我有这样的代码:

$(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的初学者,请帮助我。

6 个答案:

答案 0 :(得分:13)

dataType: "json"放入jquery调用中。 resp将是一个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。在这种情况下,不建议使用本地技巧,因为有些局部变量可能无法在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

答案 1 :(得分:5)

如何创建dict并解析为json:

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

答案 2 :(得分:1)

你有一个错字:

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

应该是

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

另外,关于csrf,你必须使用这样的标题:

    $.ajax({
            url: "some-url",
            headers: {'X-CSRFToken': '{{ csrf_token }}'},

答案 3 :(得分: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())

答案 4 :(得分:0)

如果无效,请在功能

之前加上“@csrf_exempt”
from django.views.decorators.csrf import csrf_exempt

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

答案 5 :(得分:0)

这样做......(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 {
            ...
        }
    }
});