如何在Django中响应Ajax请求 [英] How to response ajax request in Django

查看:56
本文介绍了如何在Django中响应Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

$(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中查看:

and view in 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的初学者,请帮助我。

Where is my mistake? I'm a beginner in Django, please help me.

推荐答案

输入 dataType: json 在jquery调用中。 resp将是一个javascript对象。

Put dataType: "json" in the jquery call. The resp will be a javascript object.

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

In Django, you must return a json-serialized dictionnary containing the data. The content_type must be application/json. In this case, the locals trick is not recommended because it is possible that some local variables can not be serialized in json. This wil raise an exception. Please also note that is_ajax is a function and must be called. In your case it will always be true. I would also test request.method rather than 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

这篇关于如何在Django中响应Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆