user2492364
user2492364

Reputation: 6693

How do django send ajax response?

Here is my code ,I got response is 200 OK but ajax came to error part I can't figure it out

My html:

    $(".statics").click(function(){
        var name = $(this).attr("data-name");

        $.ajax({
            url: 'statics/',
            data: {
                'name':name
            },
            type: 'POST',
            async: false,
            dataType: 'json',
            success: function(dataArr){
                console.log("ssss:",dataArr)
                if(dataArr == "IS_PASS"){
                    alert('PASS!');
                }else if(dataArr == "NOT_PASS"){
                    alert('NOT_PASS');
                } 
            },
            error: function(ts){
                console.log("eeee:",ts)
                alert('fail');
            },
        });
    });

My views.py

def statics_r(request):
    if request.is_ajax():
        name = request.POST['name']

        ...

        if is_pass:
            return HttpResponse("IS_PASS")
        else:             
            return HttpResponse("NOT_PASS")

And the console is : eeee: Object {readyState: 4, responseText: "NOT_PASS", status: 200, statusText: "OK"}
Why it is not success???

Upvotes: 1

Views: 1341

Answers (1)

Sayse
Sayse

Reputation: 43300

For an ajax response, you should be returning json, the easiest way is to use the JsonResponse class instead of HttpResponse, or set the content_type

HttpResponse("{'result': 'IS_PASS'}", content_type="application/json")

You would need to adjust your success function to access the results, i.e dataArr.result

Upvotes: 2

Related Questions