Skip to content

Instantly share code, notes, and snippets.

@shreyansb
Created March 12, 2012 21:38
Show Gist options
  • Select an option

  • Save shreyansb/2024839 to your computer and use it in GitHub Desktop.

Select an option

Save shreyansb/2024839 to your computer and use it in GitHub Desktop.
jsonp guide
### step 1. write a javascript function that inserts a script tag
### into the <head> with the URL you want to get.
### make sure this url contains the argument callback, e.g.
### var url = http://splitmyri.de/cofi?lat=12.34&lon=45.67&callback=deal_with_request
load_jsonp_script = function(url) {
/* makes a jsonp request for url */
var e = document.createElement('script');
e.setAttribute('language','javascript');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', url);
var parent = document.head
parent.appendChild(e);
};
### step 2. the html will have this empty <script> tag
<html>
<head>
<script language='javascript' type='text/javascript'
src='http://splitmyri.de/cofi?lat=12.34&lon=45.67&callback=deal_with_request'>
</script>
</head>
<body>
</body>
</html>
### step 3. the server will get a GET request. it should return the json data 'wrapped' in
### the callback function, e.g.
def get(self):
callback = self.get_argument('callback', None)
resp_data = {'name':'asha'}
if callback:
resp_str = str(callback) + '(' + simplejson.dumps(resp_data) + ');'
self.write(resp_str)
else:
self.write(resp_data)
### step 4. the html will now look like this
<html>
<head>
<script language='javascript' type='text/javascript'
src='http://splitmyri.de/cofi?lat=12.34&lon=45.67&callback=deal_with_request'>
deal_with_request({'name':'asha'});
</script>
</head>
<body>
</body>
</html>
### step 5. the callback function in javascript will get called with the
### json response as an argument. the function could look like this
deal_with_response = function(resp) {
console.log(resp); // prints out the resp to the browser's console, which you can open with command-alt-J
// will print {'name':'asha'} to the console
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment