A natural fit for the JSON Utility is working with the Connection Manager. In this example, we'll request JSON data from the server using Connection Manager's asyncRequest
and parse the resulting JSON string data for processing.
Click the Get Messages button to send the request to the server.
The JSON utility is an extension of YAHOO.lang
. Load the JSON Utility by including these tags:
1 | <script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo/yahoo-min.js"></script> |
2 | <script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/json/json-min.js"></script> |
view plain | print | ? |
YAHOO.lang.JSON.parse
in the success handlerPass the XHR responseText
to YAHOO.lang.JSON.parse
and capture the return value. Note that the parse method can throw a SyntaxError
exception, so be sure to wrap the call in a try/catch
block.
1 | var callbacks = { |
2 | // Successful XHR response handler |
3 | success : function (o) { |
4 | var messages = []; |
5 | |
6 | // Use the JSON Utility to parse the data returned from the server |
7 | try { |
8 | messages = YAHOO.lang.JSON.parse(o.responseText); |
9 | } |
10 | catch (x) { |
11 | alert("JSON Parse failed!"); |
12 | return; |
13 | } |
14 | |
15 | // The returned data was parsed into an array of objects. |
16 | // Add a P element for each received message |
17 | for (var i = 0, len = messages.length; i < len; ++i) { |
18 | var m = messages[i]; |
19 | var p = document.createElement('p'); |
20 | var message_text = document.createTextNode( |
21 | m.animal + ' says "' + m.message + '"'); |
22 | p.appendChild(message_text); |
23 | msg_section.appendChild(p); |
24 | } |
25 | }, |
26 | |
27 | ... |
28 | }; |
29 | |
30 | // Make the call to the server for JSON data |
31 | YAHOO.util.Connect.asyncRequest('GET',"assets/jsonConnect.php", callbacks); |
view plain | print | ? |
The parse
method returns the native JavaScript object representation of the string data returned from the asyncRequest
. In this case, the data is an array of object literals in this form:
1 | [ |
2 | { "animal" : "Cat", "message" : "Meow" }, |
3 | { "animal" : "Dog", "message" : "Woof" }, |
4 | { "animal" : "Cow", "message" : "Moo" }, |
5 | { "animal" : "Duck", "message" : "Quack" }, |
6 | { "animal" : "Lion", "message" : "Roar" } |
7 | ] |
view plain | print | ? |
INFO0ms (+0) 9:57:56 PM:global
Logger initialized
Copyright © 2008 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings