Yahoo! Developer Network Home - Help

Site Search (YDN & YUIBlog):

# YUI Library Examples: JSON Utility: JSON with Connection Manager

# JSON Utility: JSON with Connection Manager

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.

View example in new window.

## Include the JSON Utility

The JSON utility is an extension of `YAHOO.lang`. Load the JSON Utility by including these tags:

<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo/yahoo-min.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/json/json-min.js"></script>

## Use `YAHOO.lang.JSON.parse` in the success handler

Pass 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.

var callbacks = { // Successful XHR response handler success : function (o) { var messages = []; // Use the JSON Utility to parse the data returned from the server try { messages = YAHOO.lang.JSON.parse(o.responseText); } catch (x) { alert("JSON Parse failed!"); return; } // The returned data was parsed into an array of objects. // Add a P element for each received message for (var i = 0, len = messages.length; i < len; ++i) { var m = messages[i]; var p = document.createElement('p'); var message_text = document.createTextNode( m.animal + ' says "' + m.message + '"'); p.appendChild(message_text); msg_section.appendChild(p); } }, ... }; // Make the call to the server for JSON data YAHOO.util.Connect.asyncRequest('GET',"assets/jsonConnect.php", callbacks);

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:

[ { "animal" : "Cat", "message" : "Meow" }, { "animal" : "Dog", "message" : "Woof" }, { "animal" : "Cow", "message" : "Moo" }, { "animal" : "Duck", "message" : "Quack" }, { "animal" : "Lion", "message" : "Roar" } ]

### YUI Logger Output:

### JSON Utility Examples:

- JSON with Connection Manager

### More JSON Utility Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2008 Yahoo! Inc. All rights reserved.

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