Using the Get Utility to Get a Script File with JSON-formatted Contents
Here, we'll use the YUI Get Utility to retrieve data via the Yahoo! Search Site-Explorer web service, one of many Yahoo! APIs that support JSON.
First, we create a plain HTML form that will work for users who do not have JavaScript enabled:
With this in place, we can progressively enhance the form to create an in-page interaction for users with JavaScript turned on.
The most important JavaScript piece here is the method that we fire on form submission. This method triggers our call to the Get Utility. This method, called getSiteExplorerData
, accomplishes four things:
- It loads a transitional state for the display, alerting the user to the fact that data is being retrieved as a result of her action (line 7ff);
- It prepares the URL that will be passed to the Get Utility (line 13ff);
- It calls the Get Utility, passing in the URL of the script resource to load (in this case, the URL of our web service with the relevant paramaters assembled in the querystring) (line 22ff);
- It specifies the callback (line 23) and the scope in which the callback should run (line 24). Note that in this example the web service itself provides callback functionality, allowing us to pass a globally accessible callback function name as one of the parameters of the REST API; you can see this reference in line 16 below. As a result, we're making direct use of the intrinsic web service callback in this example and just stubbing out the built-in Get Utility callback for the sake of illustration.
The full JavaScript codeblock for this example reads as follows: