4

I'm new to JQuery and maybe this is a n00b question. And also my English is not the best.

I wrote a service in my Google App Engine application who delivers data in JSON format, which works OK, but I wasn't able to parse that JSON data using JQuery:


var url= 'myapp.appspot.com/myservice.json?someparams';
$.getJSON(url, function(json){
    alert("Success parsing JSON");  // I never reached this code 
    ....
});

After a few days of reading posts and tutorials I felt into this SlideShare: http://www.slideshare.net/andymckay/cross-domain-webmashups-with-jquery-and-google-app-engine

While reading slide 23 I noticed about the "callback=?" parameter and I tried the code in slide 42:


class MyJSONHandler(webapp.RequestHandler):
    def get(self):
        ## Retrieve some data from DB or MemCached
        jsonData = json.dumps(data)
        if self.request.get('callback'):
            self.response.out.write('%s(%s)' % (self.request.get('callback'), jsonData))
        else:
            self.response.out.write(jsonData)

And in the JQuery function:


$.getJSON(url+'&callback=?', function(json){
    alert("Success parsing JSON");  // Now i'm here !!
    ....
});

My question is:

Why is the "callback" parameter necessary to make this work? What difference does the '?("MyJSON": [{"a-lot" : "of-data"}])' makes??

Thanks you all.

alfonso.kim
  • 2,844
  • 4
  • 32
  • 37

4 Answers4

2

The callback parameter is used to implement JSONP.

jQuery's getJSON method creates a <script> tag that point to the URL you give it.
The URL is expected to return a call to the function specified in the callback parameter, passing the data as a parameter.

Unlike normal AJAX requests, JSONP requests can be made across domains.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

If you are accessing your service from another domain using AJAX, the browser won't allow that. Using this technique gets around it by dynamically embedding a script tag with the src attribute set to the requested URL, and the body of the script calls your function name passed in, passing it your data.

Here's a great explanation of the process: http://en.wikipedia.org/wiki/JSON#JSONP

Matt King
  • 2,146
  • 15
  • 8
0

It's called JSONP.

You can look here: What is JSONP all about?

Hope it helps

Community
  • 1
  • 1
alexl
  • 6,841
  • 3
  • 24
  • 29
0

The technique is called JSONP: JSON with Padding and is used to circumvent the same-origin policy.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143