JSON, JavaScript Object Notation, like Ajax, is not a programming lan-guage, but a subset of JavaScript.. First, you had to understand how XML structures its data, and next how to creat
Trang 118.5 Ajax and JSON
What is JSON? JSON, JavaScript Object Notation, like Ajax, is not a programming
lan-guage, but a subset of JavaScript It is a text-based format that provides an easy way to
exchange and parse data over a network Although JSON was originally tied to
Java-Script, it is language independent and is now used by Ruby, PHP, C++, Python, Java, Perl,
and so on The JSON format is often used for serialization and transmitting structured
data with Ajax
If you recall, in Example 18.11 when using Ajax and XML, there was a lot involved
First, you had to understand how XML structures its data, and next how to create the
XML DOM object when the server returns the contents of the XML file, and finally how
to use the DOM to parse the data JSON offers a nice alternative to using XML Instead
JSON represents data as an array or associative array (JavaScript object) and any
lan-guage that supports this representation of data can use it
Most modern browsers are providing an implementation of native JSON so that you
can use parse and string methods provided by the browser to handle JSON data For
example, Firefox 3.5, Internet Explorer 8, Google Chrome, and Apple Safari have
intro-duced support for native JSON, and the ECMAScript Fifth Edition (ES5) Draft
Specifi-cation is being finalized to support it Using native JSON is much faster and convenient
than importing libraries There are a number of Ajax frameworks including Yahoo! UI
<p>
<input type="button" value="submit"
onClick="ajaxFunction()"; />
</form>
<div id="message" class="divStyle">
</div>
</p>
</body>
</html>
E X P L A N A T I O N
1 When the XMLHttpRequest object is initialized, the open() method takes two
pa-rameters in this example: the HTTP method is POST, and the URL is the name of
the server-side PHP script that will process form input sent by the server The
de-fault is asynchronous, true, specified as a third parameter.
2 With the POST method another header is sent to the server specifying the
“Con-tent-type”
3 Instead of sending the query string as a set of parameters to the open() method,
they are sent to the server by the send() method.
4 This is where the HTML form starts There are no attributes
E X A M P L E 1 8 1 7 (C O N T I N U E D)
Trang 2Library, jQuery, Dojo, and mootools that support JSON The JSON Web site provides a
short and succinct discussion on the JSON technology (see Figure 18.19)
18.5.1 JSON Data Structures
JSON is based on two data structures we discussed in Chapters 8 and 9: arrays and objects
As you might recall, the array is indexed by numbers or strings, and the object consists of
properties and their corresponding values It is possible to nest these data structures, so you
might have an array of objects, an array of arrays, an object with nested properties and
val-ues, and so on For both of these structures, we use the literal notation
Figure 18.19 The JSON Web site.
Trang 318.5.2 Steps to Use JSON
Create a json File. To use JSON, the object literal or array will be placed in a file
named with a json extension (see Chapter 8 to review object literals) The object or
array will not be named in the file It would look like this:
{ "namev: undefined,
"rank": "captain",
"picturev: "keeweeboy.jpg",
"salary": 50000,
"enlisted": true }
E X A M P L E ( SA M P L E CO D E)
Example: (JavaScript array)
var friends = [ “John”, “Jane”, “Niveeta”, “Su” ];
Example: (JavaScript object literal)
var soldier = {
name: undefined, rank: "captain", picture: "keeweeboy.jpg", salary: 50000,
enlisted: true
}
Table 18.5 JSON’s Basic Types
Data Type Example
Number 5, 5.435
String “John Doe”, ‘red’
Boolean true or false
Array [ 1,2,3,4.5 ]
[“Bob”,”Jim”,”Joe”]
Object { “Name”: “John”,
“Age” : 35, “Status”: true, }
Trang 4Create the Ajax Program. The Ajax program will make a request to the server to
get text in the json file The server will return the text in the requestResponseText
prop-erty of the Ajax request object Next Ajax must convert the JSON text into a JavaScript
object (or array) To accomplish this, we can use the JavaScript built-in eval() function,
as long as security is not an issue For our demo it is not, because Ajax communication
is permitted within this domain where the page originated, and therefore, trusted (Later
we will download the JSON library, json2, to accomplish the same task.)
The eval() function evaluates the text and creates a JavaScript data structure,
consist-ing of key/value pairs, either an array or object
var myObject = eval('(' + myJSONtext + ')');
Now with the dot notation, we can get the values associated with the keys; for
exam-ple,
name = myObject.name // object notation
color = myObject[0] // array notation
After the data has been parsed and stored in variable, it is ready to be displayed in the
browser
Steps for Using Ajax and a JSON Array
E X A M P L E 1 8 1 8
1 The JSON text file, "colors.json" contains the following array:
[ "red", "blue", "green", "yellow" ]
-2 The Ajax program requests the file and evals the response.
// Segment from the Ajax program
function getXMLContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var colors = eval('('+httpRequest.responseText +')') ;
alert(colors);
// alert("I like "+ colors[3]) Prints "yellow"
}
else {
alert('There was a problem with the request.');
}
}
}
Continues
Trang 5Steps for Using Ajax and a JSON Object
3 After the eval() evaluates the string returned from the server, it
is converted into an array and displayed below:
E X A M P L E 1 8 1 9
1 The JSON text file, "person.json" contains an object literal:
{ "Name": "Joe Shmoe",
"Salary": 100000.50,
"Age": 35,
"Married": true
}
-2 The Ajax program requests the file and evals the response:
// Segment from the Ajax program
function getXMLContents(httpRequest) {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
var person = eval('('+httpRequest.responseText +')') ; var name=person.Name;
var salary=person.Salary;
var age=person.Age;
var married=person.Married;
alert("Name: "+name +
"\nSalary: " + salary +
"\nAge: " + age +
"\nMarried: "+ married );
}
else {
alert('There was a problem with the request.');
}
}
}
-E X A M P L -E 1 8 1 8 (C O N T I N U E D)
Trang 618.5.3 Putting It All Together with JSON
In the next set of examples, we will create a JSON text file, with the structure of a
Java-Script object (in fact, any program employing hashes or associative arrays could read
this file), use an Ajax program to request the file and, after getting a response from the
server, read and parse the JSON data with JavaScript’s eval() function, then place the
parsed data in a div container and display it (shown in Figure 18.20).
The JSON File (ajaxCar.json)
3 Output after the eval().
E X A M P L E 1 8 2 0
1 { "make":"Honda Civic",
"year":2006,
"price":18000,
2 "owner":{
"name":"Henry Lee",
"cellphone": "222-222-2222",
3 "address":{"street": "10 Main",
"city": "San Francisco",
"state": "CA"
} },
"dealer": "SF Honda"
4 }
E X P L A N A T I O N
1 This is a JSON object consisting of properties and their values (key/value pairs)
2 The owner property has nested properties If the object is named “car”, then to get
the cell phone number for the owner, the dot notation is used to separate the
prop-erties; for example, car.owner.cellphone will get the value “222-222-2222”.
Continues
E X A M P L E 1 8 1 9 (C O N T I N U E D)