user1454693
user1454693

Reputation: 367

AJAX failing on get request: JSONP

I have a rest server running (python bottle) on the same host that is running my django application. From my django application I am doing a get request using ajax, but the request is failing even though I can see the status of the request succeeding on my rest server(returns code 200, success)

My Ajax code:

            $.ajax({
               url: 'http://hostname:port/ListVms/',
               crossDomain: true, 
               contentType: "application/json",
               dataType: 'jsonp',
               success: function(data) {
                   alert('worked');
               },
               error: function() {
                   alert("Sorry, error retrieving!");
               }
           });

Python Rest method:

            @route('/ListVms/', method='GET')
            def get_event():
                return json.dumps(JS)

Output from the rest service:

            [22/Aug/2012 10:25:45] "GET /ListVms/?callback=jQuery17102901058990901989_1345656355311&_=1345656355356 HTTP/1.1" 200 44

Upvotes: 2

Views: 481

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

I'm guessing your server is returning JSON, like this:

{ "abc": 123 }

This format is incompatible with JSONP. JSONP requires a callback function that the JSON is passed to. The callback function is passed to your server in that query string.

So using JSONP the browser plunks down a script tag like this:

<script src="http://hostname:port/ListVms/?callback=jQuery17102901058990901989_1345656355311"></srcipt>

And your server should respond with this:

jQuery17102901058990901989_1345656355311({
  "abc": 123
});

Typically servers that serve JSON and want to support JSONP have a conditional that looks kind of like this:

if queryString.callback
  render queryString.callback + "(" + jsonData + ")"
else
  render jsonData

Upvotes: 5

Related Questions