views:

67

answers:

1

I am trying to load json generated by my django app. It works when I save the json output and load it from a static file. However, when I make a call to a server it returns null.

JSON

{"users": [
    {
        "id": 1,
        "name": "arnold"
    }, 
    {
        "id": 2,
        "name": "frankie"
    }
]}

Ajax call

$.ajax({
    url: "http://localhost:8000/json",  //vs. json.js
    dataType: 'json',
    type: 'get',
    timeout: 20000,
    error: function() {
        alert("error");
    },
    beforeSend: function() {
        alert("beforeSend");
    },
    complete: function() {
        alert("complete");
    },
    success: function(data) {
        alert(data.users[0].name);
    }
});

view.py

return HttpResponse(simplejson.dumps(data), content_type = 'application/json; charset=utf8')
+2  A: 

Looks like same origin policy to me. To check, you can put your test html on the server (localhost:8000), load it from there and see if it works.

To fix, you can use dataType 'jsonp' or 'script'. For example, for jsonp you only need to enclose response in js call: random_callback(your_json_here); where random_callback is value of 'callback' request parameter (generated by jquery).

More on the topic: http://api.jquery.com/jQuery.ajax/

Nikita Rybak