Back to the index of articles and examples

YQL DataSource

A YUI3 version of this example is also available

We create a very simple to use function to fetch data from a YQL query and fill a given container with it, formatted via a template string. The function is used like this:

The first argument is a reference to the HTML that will contain the formatted output, or its id, the second is the YQL query and the third the template to be used. The names of the fields, enclosed in curly brackets are the placeholders for the retrieved data. For nested fields, the placeholders can contain the full name with dots, just as YQL uses them.

The function is very simple:

First we normalize argument config to ensure it is an object literal. Variable s is a shortname for the YAHOO.lang.substitute method because, since it is going to be used repeatedly in the loop, it makes sense to resolve it only once. Variable output will contain the formatted output, an array item per record fetched.

The first argument to the YQLDataSource constructor is the URL of the YQL web service, which defaults to its standard public address. We add the possiblity of specifying a different address in the YQLWebService configuration attribute. We pass the rest of the configuration options to the DataSource as well. We will rarely use this. The reply is always of type JSON and YQLDataSource takes all the fields it finds. It assumes the programmer will be prudent in specifying no more fields than are actually required; please, do avoid using select *. The only reason to use the responseSchema.fields configuration option would be to specify parsers for the data, otherwise, whatever it receives will be available.

We immediately call DataSource's sendRequest method with the query and provide the success callback which simply loops through the results list using substitute to pile up the formatted results on output, which we finally insert into the given container