YUI 3.x Home -

YUI Library Examples: IO: Cross-Domain JSON Transaction — Retrieving a News Feed from Yahoo! Pipes

IO: Cross-Domain JSON Transaction — Retrieving a News Feed from Yahoo! Pipes

In the example below, IO is employed to make a cross-domain request to Yahoo! Pipes. The output of the Pipe is an RSS-style feed formatted as JSON. We pass that output to the JSON Utility's parse method for sanitization and then display the contents of the Pipe in a list.

The cross-domain approach obviates the need for a server-side proxy, making it faster. And the use of IO in place of a script node allows us to retrieve the JSON data as a string and execute JSON.parse against it, making it safer to use; a script node would evaluate immediately in the global scope as soon as it was loaded.

  • Content from Yahoo! Pipes feed will display here.

Implementing a Simple Cross-Domain Request for JSON Data

In this example, we begin with a YUI instance that loads the IO and JSON modules:

  1. //Create a YUI instance including support for IO and JSON modules:
  2. YUI({base:"../../build/", timeout: 10000}).use("io-xdr", "substitute", "json-parse", function(Y) {
  3. // Y is the YUI instance.
  4. // The rest of the following code is encapsulated in this
  5. // anonymous function.
  6. });
//Create a YUI instance including support for IO and JSON modules:
YUI({base:"../../build/", timeout: 10000}).use("io-xdr", "substitute", "json-parse", function(Y) {
	// Y is the YUI instance.
	// The rest of the following code is encapsulated in this
	// anonymous function.
});

We'll also get a Node reference to the container we'll be using to output the data we retrieve:

  1. //element #output:
  2. var output = Y.Node.get("#output ul");
//element #output:
var output = Y.Node.get("#output ul");

Next, we configure IO's cross-domain interface for this YUI instance. Flash is the underlying mechansim used here. Be sure to configure the src property to point to your IO.swf file.

  1. //Configure the cross-domain protocol:
  2. var xdrConfig = {
  3. id:'flash', //We'll reference this id in the xdr configuration of our transaction.
  4. yid: Y.id, //The yid provides a link from the Flash-based XDR engine
  5. //and the YUI instance.
  6. src:'../../build/io/IO.swf?t=' + new Date().valueOf().toString() //Relative path to the .swf file from the current page.
  7. };
  8. Y.io.transport(xdrConfig);
//Configure the cross-domain protocol:
var xdrConfig = {
    id:'flash', //We'll reference this id in the xdr configuration of our transaction.
    yid: Y.id,  //The yid provides a link from the Flash-based XDR engine
                //and the YUI instance.
    src:'../../build/io/IO.swf?t=' + new Date().valueOf().toString() //Relative path to the .swf file from the current page.
};
Y.io.transport(xdrConfig);

The configuration for our specific IO transaction contains a reference to the xdr configuration we created above and specifies that there will not be a need to process the response as XML (we're getting JSON instead):

  1. var cfg = {
  2. method: "GET",
  3. xdr: {
  4. use:'flash', //This is the xdrConfig id we referenced above.
  5. responseXML:false //we're using JSON -- marginally faster, and
  6. //supported by the Pipes API
  7. },
  8. on: {
  9. //Our event handlers previously defined:
  10. start: handleStart,
  11. success: handleSuccess,
  12. failure: handleFailure
  13. }
  14. };
var cfg = {
    method: "GET",
    xdr: {
        use:'flash', //This is the xdrConfig id we referenced above.
        responseXML:false //we're using JSON -- marginally faster, and
                          //supported by the Pipes API
    },
    on: {
        //Our event handlers previously defined:
        start: handleStart,
        success: handleSuccess,
        failure: handleFailure
    }
};

The final step is to make the request:

  1. var obj = Y.io(
  2. //this is a specific Pipes feed, populated with cycling news:
  3. "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json",
  4. cfg
  5. );
var obj = Y.io(
    //this is a specific Pipes feed, populated with cycling news:
    "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json",
    cfg
);

Full Script

The full script source for this example is as follows:

  1. YUI({base:"../../build/", timeout: 10000}).use("io-xdr", "substitute", "json-parse",
  2.  
  3. function(Y) {
  4.  
  5. //Data fetched will be displayed in a UL in the
  6. //element #output:
  7. var output = Y.Node.get("#output ul");
  8.  
  9. //Configure the cross-domain protocol:
  10. var xdrConfig = {
  11. id:'flash', //We'll reference this id in the xdr configuration of our transaction.
  12. yid: Y.id, //The yid provides a link from the Flash-based XDR engine
  13. //and the YUI instance.
  14. src:'../../build/io/io.swf' //Relative path to the .swf file from the current page.
  15. };
  16. Y.io.transport(xdrConfig);
  17.  
  18. //Event handler called when the transaction begins:
  19. var handleStart = function(id, a) {
  20. Y.log("io:start firing.", "info", "example");
  21. output.set("innerHTML", "<li>Loading news stories via Yahoo! Pipes feed...</li>");
  22. }
  23.  
  24. //Event handler for the success event -- use this handler to write the fetched
  25. //RSS items to the page.
  26. var handleSuccess = function(id, o, a) {
  27.  
  28. //We use JSON.parse to sanitize the JSON (as opposed to simply eval'ing
  29. //it into the page):
  30. var oRSS = Y.JSON.parse(o.responseText);
  31.  
  32. //From here, we simply access the JSON data from where it's provided
  33. //in the Yahoo! Pipes output:
  34. if (oRSS && oRSS.count) {
  35.  
  36. var s = "<!--begin news stories fetched via Yahoo! Pipes-->",
  37. //t in this case is our simple template; this is fed to
  38. //Y.Lang.substitute as we loop through RSS items:
  39. t = "<li><a href='{link}'>{title}</a>, {pubDate}</li>";
  40.  
  41. for (var i=0; i<oRSS.count; i++) {
  42. s += Y.Lang.substitute(t, oRSS.value.items[i]);
  43. }
  44.  
  45. //Output the string to the page:
  46. output.set("innerHTML", s);
  47.  
  48. } else {
  49. //No news stories were found in the feed.
  50. var s = "<li>The RSS feed did not return any items.</li>";
  51. }
  52. }
  53.  
  54. //In the event that the HTTP status returned is > 399, a
  55. //failure is reported and this function is called:
  56. var handleFailure = function(id, o, a) {
  57. Y.log("ERROR " + id + " " + a, "info", "example");
  58. }
  59.  
  60. //With all the aparatus in place, we can now configure our
  61. //io call.
  62. var cfg = {
  63. method: "GET",
  64. xdr: {
  65. use:'flash', //This is the xdrConfig id we referenced above.
  66. responseXML:false //we're using JSON -- marginally faster, and
  67. //supported by the Pipes API
  68. },
  69. on: {
  70. //Our event handlers previously defined:
  71. start: handleStart,
  72. success: handleSuccess,
  73. failure: handleFailure
  74. }
  75. };
  76.  
  77. //Wire the buttton to a click handler to fire our request each
  78. //time the button is clicked:
  79. var handleClick = function(o) {
  80. Y.log("Click detected; beginning io request to Yahoo! Pipes.", "info", "example");
  81. var obj = Y.io(
  82. //this is a specific Pipes feed, populated with cycling news:
  83. "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json",
  84. cfg
  85. );
  86. }
  87.  
  88. //add the clickHandler as soon as the xdr Flash module has
  89. //loaded:
  90. Y.on('io:xdrReady', function() {
  91. var fetch = Y.Node.get("#fetch");
  92. fetch.set("disabled", false);
  93. Y.on("click", handleClick, fetch);
  94. });
  95. }
  96. );
YUI({base:"../../build/", timeout: 10000}).use("io-xdr", "substitute", "json-parse",
 
	function(Y) {
 
		//Data fetched will be displayed in a UL in the
		//element #output:
		var output = Y.Node.get("#output ul");
 
		//Configure the cross-domain protocol:
		var xdrConfig = {
			id:'flash', //We'll reference this id in the xdr configuration of our transaction.
			yid: Y.id,  //The yid provides a link from the Flash-based XDR engine
						//and the YUI instance.
			src:'../../build/io/io.swf' //Relative path to the .swf file from the current page.
		};
		Y.io.transport(xdrConfig);
 
		//Event handler called when the transaction begins:
		var handleStart = function(id, a) {
			Y.log("io:start firing.", "info", "example");
			output.set("innerHTML", "<li>Loading news stories via Yahoo! Pipes feed...</li>");
		}
 
		//Event handler for the success event -- use this handler to write the fetched
		//RSS items to the page.
		var handleSuccess = function(id, o, a) {
 
			//We use JSON.parse to sanitize the JSON (as opposed to simply eval'ing
			//it into the page):
			var oRSS = Y.JSON.parse(o.responseText);
 
			//From here, we simply access the JSON data from where it's provided
			//in the Yahoo! Pipes output:
			if (oRSS && oRSS.count) {
 
				var s = "<!--begin news stories fetched via Yahoo! Pipes-->",
					//t in this case is our simple template; this is fed to
					//Y.Lang.substitute as we loop through RSS items:
					t = "<li><a href='{link}'>{title}</a>, {pubDate}</li>";
 
				for (var i=0; i<oRSS.count; i++) {
					s += Y.Lang.substitute(t, oRSS.value.items[i]);
				}
 
				//Output the string to the page:
				output.set("innerHTML", s);
 
			} else {
				//No news stories were found in the feed.
				var s = "<li>The RSS feed did not return any items.</li>";
			}
		}
 
		//In the event that the HTTP status returned is > 399, a
		//failure is reported and this function is called:
		var handleFailure = function(id, o, a) {
			Y.log("ERROR " + id + " " + a, "info", "example");
		}
 
		//With all the aparatus in place, we can now configure our
		//io call.
		var cfg = {
			method: "GET",
			xdr: {
				use:'flash', //This is the xdrConfig id we referenced above.
				responseXML:false //we're using JSON -- marginally faster, and
								  //supported by the Pipes API
			},
			on: {
				//Our event handlers previously defined:
				start: handleStart,
				success: handleSuccess,
				failure: handleFailure
			}
		};
 
		//Wire the buttton to a click handler to fire our request each
		//time the button is clicked:
		var handleClick = function(o) {
			Y.log("Click detected; beginning io request to Yahoo! Pipes.", "info", "example");
			var obj = Y.io(
				//this is a specific Pipes feed, populated with cycling news:
				"http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json",
				cfg
			);
		}
 
		//add the clickHandler as soon as the xdr Flash module has
		//loaded:
		Y.on('io:xdrReady', function() {
			var fetch = Y.Node.get("#fetch");
			fetch.set("disabled", false);
			Y.on("click", handleClick, fetch);
		});
	}
);

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings