I would like to make cross domain request in the client end, so I chose JSONP. I am new to JSONP and would like to make a request to http://somedomain.com using JavaScript and not jQuery. It would be very helpful for my development if I get sample snippet to make and handle a request using JSONP in JavaScript.
Asked
Active
Viewed 4,280 times
7
-
Plenty of info here: http://en.wikipedia.org/wiki/JSONP – sje397 May 06 '11 at 06:51
1 Answers
11
Here's a small example fetching data from a google spreadsheet:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>jsonp</title>
</head>
<body>
<span></span>
<script>
//this function is the callback, it needs to be a global variable
function readResponse(response){
document.getElementsByTagName('SPAN')[0].innerHTML = response.feed.entry.length + ' entries returned';
console.log(response);
}
(function(){
//note the "readResponse" at the end
var src = 'http://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json-in-script&callback=readResponse',
script = document.createElement('SCRIPT');
script.src = src;
document.body.appendChild(script);
})();
</script>
</body>
</html>
One comment related to this example. If you want to play with your own google spreadsheet, you need to both share it as public, and publish it.

Mic
- 24,812
- 9
- 57
- 70
-
Great example! Here's another one.. it's a JSBin that can be used to [fiddle with JSONP](http://jsbin.com/omujex/10/edit) from Wikipedia. It was referenced in [this answer](http://stackoverflow.com/questions/15293680/fetch-random-excerpt-from-wikipedia-javascript-client-only/15293681#15293681). – rkagerer Mar 08 '13 at 14:10