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-xdr, json-parse, substitute and node modules. The io-xdr module is the key module. The other modules are used to process and output the results:

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

Copyright © 2011 Yahoo! Inc. All rights reserved.

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