Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

python - How to response ajax request in Django

I have code like this:

$(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");
            }
        });
    });
});

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())

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
});

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())

UPDATE : As mentioned by Jurudocs, csrf_token can also be a cause I would ecommend to read : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...