5
<title>Example: JSON with Y.io</title>
6
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700">
7
<link rel="stylesheet" href="../../build/cssgrids/grids-min.css">
8
<link rel="stylesheet" href="../assets/css/main.css">
9
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
10
<script src="../../build/yui/yui-min.js"></script>
15
<h1>Example: JSON with Y.io</h1>
20
<div class="yui3-u-3-4">
22
<div class="content"><div class="intro">
24
A natural fit for the JSON module is to work with IO to parse JSON messages received via XMLHttpRequest (XHR). In this example, we'll request JSON data from the server using the <a href="http://yuilibrary.com/yui/docs/api/classes/IO.html#method_io"><code>Y.io()</code></a> method and parse the resulting JSON string data.
28
<div class="example yui3-skin-sam">
29
<div id="demo" class="yui3-skin-sam">
30
<p>Click the <em>Get Messages</em> button to send the request to the server; the response will be displayed below the button.</p>
31
<p><button>Get Messages</button></p>
32
<div id="demo-messages"></div>
36
// Create business logic in a YUI sandbox using the 'io' and 'json' modules
37
YUI().use("node", "io", "dump", "json-parse", function (Y) {
39
// capture the node that we'll display the messages in
40
var target = Y.one('#demo-messages');
42
// Create the io callback/configuration
48
success : function (x,o) {
49
Y.log("RAW JSON DATA: " + o.responseText);
54
// Process the JSON data returned from the server
56
messages = Y.JSON.parse(o.responseText);
59
alert("JSON Parse failed!");
63
Y.log("PARSED DATA: " + Y.Lang.dump(messages));
65
// The returned data was parsed into an array of objects.
66
// Add a P element for each received message
67
for (i=0, l=messages.length; i < l; ++i) {
68
html += '<p>' + messages[i].animal + ' says "' +
69
messages[i].message + '"</p>';
72
// Use the Node API to apply the new innerHTML to the target
73
target.setContent(html);
76
failure : function (x,o) {
77
alert("Async call failed!");
83
// Attach a click event listener to the button #demo_btn to send the request
84
Y.one('#demo button').on('click',function (e) {
85
// Make the call to the server for JSON data
86
Y.io("../assets/json/json-connect-response.json", callback);
94
<h2>Use <code>Y.JSON.parse</code> in the <code>success</code> handler</h2>
97
Pass the XHR <code>responseText</code> to <code>Y.JSON.parse()</code> and capture the return value. Note that the <code>parse()</code> method can throw a <code>SyntaxError</code> exception, so be sure to wrap the call in a <code>try/catch</code> block.
100
<pre class="code prettyprint lang-javascript">Y.io('../assets/json/json-connect-response.json', {
102
success : function (tx, r) {
105
// protected against malformed JSON response
107
parsedResponse = Y.JSON.parse(r.responseText);
110
alert("JSON Parse failed!");
119
The <code>parse()</code> method returns the native JavaScript object representation of the string data returned from the <a href="http://yuilibrary.com/yui/docs/api/classes/IO.html#method_io"><code>Y.io()</code></a> call. In this case, the data is an array of object literals in this form:
122
<pre class="code prettyprint lang-json">[
123
{ "animal" : "Cat", "message" : "Meow" },
124
{ "animal" : "Dog", "message" : "Woof" },
125
{ "animal" : "Cow", "message" : "Moo" },
126
{ "animal" : "Duck", "message" : "Quack" },
127
{ "animal" : "Lion", "message" : "Roar" }
132
In the <code>success</code> handler we'll simply loop through this array and outputting its contents to the DOM.
135
<h2>Complete Example Source</h2>
136
<pre class="code prettyprint"><div id="demo" class="yui3-skin-sam">
137
<p>Click the <em>Get Messages</em> button to send the request to the server; the response will be displayed below the button.</p>
138
<p><button>Get Messages</button></p>
139
<div id="demo-messages"></div>
143
// Create business logic in a YUI sandbox using the 'io' and 'json' modules
144
YUI().use("node", "io", "dump", "json-parse", function (Y) {
146
// capture the node that we'll display the messages in
147
var target = Y.one('#demo-messages');
149
// Create the io callback/configuration
155
success : function (x,o) {
156
Y.log("RAW JSON DATA: " + o.responseText);
159
html = '', i, l;
161
// Process the JSON data returned from the server
163
messages = Y.JSON.parse(o.responseText);
166
alert("JSON Parse failed!");
170
Y.log("PARSED DATA: " + Y.Lang.dump(messages));
172
// The returned data was parsed into an array of objects.
173
// Add a P element for each received message
174
for (i=0, l=messages.length; i < l; ++i) {
175
html += '<p>' + messages[i].animal + ' says "' +
176
messages[i].message + '"</p>';
179
// Use the Node API to apply the new innerHTML to the target
180
target.setContent(html);
183
failure : function (x,o) {
184
alert("Async call failed!");
190
// Attach a click event listener to the button #demo_btn to send the request
191
Y.one('#demo button').on('click',function (e) {
192
// Make the call to the server for JSON data
193
Y.io("../assets/json/json-connect-response.json", callback);
197
</script></pre>
203
<div class="yui3-u-1-4">
204
<div class="sidebar">
208
<div class="sidebox">
210
<h2 class="no-toc">Examples</h2>
214
<ul class="examples">
217
<li data-description="Use JSON to parse data received via XMLHttpRequest via Y.io calls — a simple JSON use case.">
218
<a href="json-connect.html">JSON with Y.io</a>
223
<li data-description="Use the replacer and reviver parameters to reconstitute object instances that have been serialized to JSON.">
224
<a href="json-freeze-thaw.html">Rebuilding Class Instances from JSON Data</a>
229
<li data-description="Use a currency conversion calculation to add a new price member to a JSON response, demonstrating how JSON data, once retrieved, can be transformed during parsing.">
230
<a href="json-convert-values.html">Adding New Object Members During Parsing</a>
244
<div class="sidebox">
246
<h2 class="no-toc">Examples That Use This Component</h2>
250
<ul class="examples">
259
<li data-description="A basic todo list built with the Model, Model List, and View components.">
260
<a href="../app/app-todo.html">Todo List</a>
265
<li data-description="Portal style example using Drag & Drop Event Bubbling and Animation.">
266
<a href="../dd/portal-drag.html">Portal Style Example</a>
279
<script src="../assets/vendor/prettify/prettify-min.js"></script>
280
<script>prettyPrint();</script>