1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 94 docx

6 185 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 6
Dung lượng 636,03 KB

Nội dung

ptg 834 Chapter 18 • An Introduction to Ajax (with JSON) 18.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> EXPLANATION 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. EXAMPLE 18.17 (CONTINUED) From the Library of WoweBook.Com ptg 18.5 Ajax and JSON 835 Library, 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. From the Library of WoweBook.Com ptg 836 Chapter 18 • An Introduction to Ajax (with JSON) 18.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 } EXAMPLE (SAMPLE CODE) 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, } null null From the Library of WoweBook.Com ptg 18.5 Ajax and JSON 837 Create 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 EXAMPLE 18.18 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 From the Library of WoweBook.Com ptg 838 Chapter 18 • An Introduction to Ajax (with JSON) Steps 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: EXAMPLE 18.19 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.'); } } } EXAMPLE 18.18 (CONTINUED) From the Library of WoweBook.Com ptg 18.5 Ajax and JSON 839 18.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(). EXAMPLE 18.20 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} EXPLANATION 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 EXAMPLE 18.19 (CONTINUED) From the Library of WoweBook.Com . (with JSON) 18.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. "enlisted": true } EXAMPLE (SAMPLE CODE) Example: (JavaScript array) var friends = [ “John”, “Jane”, “Niveeta”, “Su” ]; Example: (JavaScript object literal) var soldier = { name: undefined,. 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

Ngày đăng: 04/07/2014, 02:21

TỪ KHÓA LIÊN QUAN