JSONP
JSONP comes from the words "JSON with padding". The padding word is there because the loaded JSON formatted data is wrapped inside a javascript function call.
How it works
JSONP utilizes dynamically created -tags. The benefit of tag is that their source can point any domain. They are not restricted by same origin policy as AJAX requests.
Web APIs that use JSON data format usually let the end user to define callback function name by passing argument as a part of web service query string.
The server generates a JSON formatted response and wraps it into a function call. The callback function is automatically called when JSON data is evaluated.
Example JSONP response:
handleTwitterData ({"results":[..json formatted data..]});
Following example utilizes JSON version of the Twitter search API.
jsonpSearch("http://search.twitter.com/search.json","handleTwitterData",keyword);
function jsonpSearch(url, callback, keyword){
var head = document.getElementsByTagName('head');
var scriptElement = document.createElement('script');
scriptElement.type = "text/javascript";
scriptElement.src = url+"?callback="+callback+"&q="+keyword;
scriptElement.id = "jsonp";
head[0].appendChild(scriptElement);
}
function handleTwitterData(data){
var tweets = data.results;
.....
}
If you are going to do multiple successive queries, you might end up situation where your widget leaks memory. That's why it is important to delete both the script tag from the DOM and the JavaScript objects as well (1).
function clearOldSearch(){
var script = document.getElementById("jsonp");
if(script) {
script.parentNode.removeChild(script); //does not really release the memory
for (var property in script) { //so delete all the properties as well
delete script[property];
}
}
}
For minimal test widget see: [TwitterIn2Min.zip](http://www.forum.nokia.com/piazza/wiki/images/0/07/TwitterIn2min.zip "http://www.forum.nokia.com/piazza/wiki/images/0/07/TwitterIn2min.zip")
Comments(0)