Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Revision as of 04:05, 26 July 2012 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Using JSONP in WRT widget

From Wiki
Jump to: navigation, search
Article Metadata
Code ExampleArticle
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

This page was last modified on 26 July 2012, at 04:05.
222 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×