user2368822
user2368822

Reputation: 31

Django/Ajax get request

I'm trying to implement client/server communication using Django and Ajax and I'm having problem with Ajax request.

Here is my view:

from django.http import HttpResponse
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

from taskmanager.models import Task
from taskmanager.serializers import TaskSerializer


class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


def task_list(request):
    if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskSerializer(tasks, many=True)
        return JSONResponse(serializer.data)

And my jquery code:

$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            type: "get",
            url: "http://127.0.0.1:8000/",
            dataType: "json",
            success: function(data){
                alert(data[0]["title"]);
            },
            error: function(){
                alert("error");
            }
        });
    });
});

Every time server returns status 200 OK, but the error function is executed. When I visit that url directly in browser I get valid json output. Even more, if I put that output in a file and reference it in ajax call url it works as intended.

P.S. Sorry for my English.

UPDATE: Also, when I view response details in FireBug it has no response body.

Response headers:

Server:WSGIServer/0.1 Python/2.7.3
Date:Fri, 10 May 2013 07:56:23 GMT 
Content-Type:application/json

UPDATE: changed AJAX url to: "http://127.0.0.1:8000/?callback=?" and now I get response body: [{"id": "518a92147c2fce152b081878", "title": "New task"}, {"id": "518a905e7c2fce1516b8f9dc", "title": "Save the galaxy"}, {"id": "518a904e7c2fce1516b8f9da", "title": "Do a barrel roll"}], status -- 200 and error -- parsererror.

Upvotes: 3

Views: 11393

Answers (2)

Ravi Aggarwal
Ravi Aggarwal

Reputation: 159

Try return HttpResponse(serializer.data, content_type='application/json') in your view.

And in your jQuery code change type: "GET" and remove dataType: "json".

Upvotes: 1

speedingdeer
speedingdeer

Reputation: 1236

I think there is an error in your js Content negotietion

instead of

dataType: "json",

use

contentType: 'application/json',

or try without this field

Upvotes: 2

Related Questions