Namespaces
Variants
Actions
Revision as of 07:05, 26 July 2012 by hamishwillee (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Using JSONP in WRT widget

Jump to: navigation, search
Article Metadata

Code Example
Article
Created: isalento (25 Nov 2009)
Last edited: hamishwillee (26 Jul 2012)

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 script -tags. The benefit of script 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 callback 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: Media:TwitterIn2Min.zip

Read more about JSONP

Ajaxian JSONP: JSON With Padding

JSONP Memory Leak

119 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved