Using YUI Get Module for cross-domain JSON

Intro

The Get Util­ity is one of the smaller YUI mod­ules. Despite its size, how and when to use it can be quite com­pli­cated. It is used with css and javascript files to pro­vide pro­gres­sive load­ing of func­tion­al­ity and cross-site data retrieval. Pro­gres­sive load­ing is a tech­nique to load resources as they are needed on the page and not before. Cross-site data retrieval is use­ful for cre­at­ing mashups, it allows you to request third party data. Unlike nor­mal ajax appli­ca­tions, secu­rity issues pre­vent you from using XML­HttpRe­quest to call third party APIs that are hosted on dif­fer­ent domains. In order to use XML­HttpRe­quests you would need to setup a proxy server hosted on your web­site. The Get Util­ity avoids this by append­ing a script or link tag directly to the page to retrieve the resource. It has the advan­tage of being light­weight, but it could also be a secu­rity issue and you shouldn’t use it with­out under­stand­ing the risks. Be sure you trust the 3rd party APIs you are call­ing and you are not expos­ing users to mali­cious javascript.

Exam­ple: Get for cross-domain JSON

The fol­low­ing exam­ple is based on the “Using JSON with Yahoo! Web Ser­vices” call­back exam­ples, but uses the Get Util­ity to request the JSON data.

First, add the YUI source files to your webpage




The method for load­ing javascript with the Get Util­ity is script. It takes a URL loca­tion for a javascript resource. Script has an optional para­me­ter for a call­back func­tion that is called once the resource is loaded. In the exam­ple, the call­back onSuccess is called by Get when the javascript resource is loaded. This call­back is dif­fer­ent from the ws_results call­back that is defined in the data request which is also called when the javascript is loaded.


function ws_results(obj) {
	alert(obj.ResultSet.totalResultsAvailable);
}
var searchDataReq = 'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&output=json&callback=ws_results';

//make Cross Domain request, callback method is onSuccess
var objTransaction = YAHOO.util.Get.script(searchDataReq,
                              { onSuccess: function() {alert("file loaded"); }});

Here is a live exam­ple run­ning this code: YUI Get Util­ity JSON Demo

No Comments

Post a Comment

Your email is never shared. Required fields are marked *