Section 7.6. Just Do It


7.6. Just Do It

Before we discuss how JSON and server-side languages like PHP get along, let's take a closer look at how you can access JSON data in your JavaScript. Here's another JSON data structure:

     {"books": [     {"title":"Hyperion", "author":"Dan Simmons", "isbn":"0553283685"},     {"title":"The Stars My Destination", "author":"Alfred Bester", "isbn:":"0679767800"},     {"title":"Black House", "author": [ "Stephen King", "Peter Straub"],     "isbn":"0345441036"},     {"title":"The Golden Compass", "author":"Philip Pullman", "isbn":"0679879242"},    ]}; 

Below are several values from the JSON structure. Your job is to write the JavaScript code that would return the value from the JSON data structure. You can assume the JSON data is in an object called jsonData.

     "Alfred Bester"            var bester = jsonData.books[1].author;We've done the first one to get you started.                               _______________________________________     "0679879242"              ________________________________________     "0345441036"              ________________________________________     "Dan Simmons"             ________________________________________     "Black House"             ________________________________________     "Peter Straub"            ________________________________________ Answers on page 390. 

I'm thrilled that JSON data is so easy to use in your JavaScript code... but it's a big pain in the butt for me and my PHP scripts to deal with. You realize that, right?

7.6.1. We did say that JSON is JavaScript

The great thing about JSON is that it's just JavaScript, so the JavaScript code in your web pages can use JSON data really easily. If you're already used to working with arrays in JavaScript, then you'll be able to use the arrays returned from a server's JSON-based response. If you're used to working with JavaScript objects, then JSON will feel really natural, too.

The bad news is that since JSON is JavaScript, languages like PHP and Perl and Java can't understand JSON without a little help. You're probably going to need a library to help you create and output JSON in your server-side scripts and programs. Then you're going to have to figure out how to use those libraries, which takes a little time and effort.

We talk about how to get one of the most popular JSON libraries for PHP working in Appendix 1.

 Here's Frank's modified PHP script... now it responds to your requests with JSON data instead of XML data. $boardsSold = $row['boardsSold']; $bootsSold = $row['bootsSold']; JSON.php is just one of several PHP libraries that lets PHP work with JSON data. $bindingsSold = $row['bindingsSold']; You'll need a new Services_JSON object to handle encoding a JSON response in PHP. require_once('JSON.php'); $json = new Services_JSON(); $vail = array('location' => 'Vail', PHP's array type is the closest thing to JSON data structures.         'boardsSold' => $vailBoards,         'bootsSold' => $vailBoots,         'bindingsSold' => $vailBindings); $santaFe = array('location' => 'Santa Fe', This takes a lot of effort.... it seemed a bit easier to output an XML response.         'boardsSold' => $santaFeBoards,         'bootsSold' => $santaFeBoots,         'bindingsSold' => $santaFeBindings); $boulder = array('location' => 'Boulder',         'boardsSold' => $boulderBoards,         'bootsSold' => $boulderBoots,         'bindingsSold' => $boulderBindings); $denver = array('location' => 'Denver',         'boardsSold' => $denverBoards,         'bootsSold' => $denverBoots,         'bindingsSold' => $denverBindings); $totals = JSON uses lots of arrays, and even arrays of arrays.   array('totals' =>         array($vail, $santaFe, $boulder, $denver)); encode() converts your PHP arrays into a JSON structure. $output = $json->encode($totals); print($output); Once you've got a JSON data structure, you can send that structure back as a response. mysql_close($conn); ?> Wanna compare JSON to XML? Flip back to Chapter 6, and compare the PHP that responds with  XML to this PHP, which responds with JSON. 

If I can convince Frank to have his scripts send my JavaScript JSON, how do I deal with his response? Do I use responseText again? Or responseXML?

7.6.2. JSON comes across as text

When servers respond with JSON, they send the data across as text. So you need to use the responseText property of your request object to get the JSON data. But JSON is meant to be used in JavaScript as an object, so you've got to convert it from text to its object form. You can do this using JavaScript's eval() function, like this:

Yeah, right. Like I want a bunch of JavaScript in my PHP scripts...

 function updatePage() {     if (request.readyState == 4) {        if (request.status == 200) { jsonData will hold the JSON data in its object form after this runs.        var jsonData = eval('(' + request.responseText + ')'); request.responseText holds the JSON data, in text form, that the server returned. eval() takes a string and converts the string of JSON data returned by the server into a JavaScript object.    // Get the updated totals from the XML response     var totalBoards = jsonData.totals[0].boardsSold +                         jsonData.totals[1].boardsSold +                         jsonData.totals[2].boardsSold +                         jsonData.totals[3].boardsSold;     var totalBoots = jsonData.totals[0].bootsSold +                         jsonData.totals[1].bootsSold +                         jsonData.totals[2].bootsSold +                         jsonData.totals[3].bootsSold;     var totalBindings = jsonData.totals[0].bindingsSold + 

Looks like JSON has some serious skills... this is a data format that isn't gonna roll over for XML.

Frequently asked questions?

Q:

Couldn't I just output JSON in my PHP script as text, and avoid using a library?

A:

If you really wanted to, yes. You'd have to know JSON pretty well to just type it in, and be sure you don't make any errors. But if you're really familiar with JSON, that might be an option for you, and you can avoid having to use the JSON libraries in your PHP scripts

One of the big advantages of using a library for JSON output, though, is that your scripters and server-side programmers don't have to learn JSON; they can use normal PHP or Java data structures, and then let the toolkit convert those structures to the JSON data format.

Q:

So I need a library to use JSON in my web apps?

A:

Your JavaScript code can use JSON without any special libraries or toolkits. But your server-side programs, which are probably written in PHP or Java or maybe Ruby, probably don't know how to work with the JSON data format without a little help. So you'll need to get a library that allows those programming languages to understand and work with JSON data.

Q:

So where can I get libraries for my server-side languages?

A:

You can visit the JSON web site at http://www.json.org to get information on most of the popular JSON libraries. There's a library for all the major programming languages, so you shouldn't have any trouble finding one that's right for you.

Q:

And if my server returns JSON, I use the responseText property to get that data?

A:

Exactly. The server returns the JSON data as text, which is easy to send over a network connection. The web browser stores text responses from servers in the request object's responseText property, so that's where you should look for a JSON response from your server.

Q:

Why do I need to use eval()?

A:

Remember, JSON is JavaScript Object Notation. JSON is a data format, but it represents data as an object, not just plain text. When you get the server's response, though, it is plain text, stored in the responseText property of your JavaScript request object.

To convert that text into an object, you need to use JavaScript's eval() function. eval() takes a string as an argument, and tries to either run that string as a command, or convert it into an object. In this case, eval() sees that you're giving it the text version of some JSON data, and returns a JSON object that you can then use in the rest of your JavaScript.

Q:

And there's no DOM tree involved, right?

A:

Right. You don't need the Document Object Model to work with JSON data.


Since JSON is just JavaScript, I can use JSON as the data format for my asynchronous requests, too, right?

You can use JSON, XML, or text in your requests to the server

You can send JSON to the server in your requests, just like you can send XML or text. But just like with XML, it's often easier to use plain text name/ value pairs to send your requests to the server.

What if I want to send objects or arrays in my request?

You should use text data for your requests whenever possible.

JSON is great with objects... ...but do you really need objects?

JSON is a great way to send objects or arrays to a server. But then the server is going to have to use a JSON library to take the data it receives, and convert it to arrays, or some other format that the server can use.

Even when you have objects, it's usually easier to represent the object's values as name/value pairs, and just send plain text to your server. In general, if you can use text for your request, you should use text for your response.




Head Rush Ajax
Head Rush Ajax (Head First)
ISBN: 0596102259
EAN: 2147483647
Year: 2004
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net