Reputation: 2900
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.
Upvotes: 4
Views: 12326
Reputation: 816472
The technique is called JSONP: JSON with Padding and is used to circumvent the same-origin policy.
Upvotes: 0
Reputation: 6851
It's called JSONP.
You can look here: What is JSONP all about?
Hope it helps
Upvotes: 0
Reputation: 2166
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
Upvotes: 1
Reputation: 887469
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.
Upvotes: 2