JSON is a lightweight format for data interchange. Easy to read and write, but also easy to machine parse and generate. AJAX is a technique for creating better, faster, and more interactive Web applications. I have previously introduced the use of JSON in the PHP language article, you can also see, for reference.
Although XML plays a pivotal role in Ajax operations, JavaScript developers quickly lose interest in it. There are serious cross-browser issues with manipulating XML in JavaScript, and extracting data from the XML structure involves traversing DOM documents, all of which require a lot of code to write. Douglas Crockford invented a data format called JSON (JavaScript Object Notation) but was able to create the same data structure as XML. The basis of JSON is a subset of JavaScript syntax, especially object and array literals. JSON is designed to build formatted data on the server and then send the data to the browser.
Because JSON is the equivalent of objects and arrays in JavaScript, it is fast and easy to access in JavaScript code, and JSON is increasingly sought after by developers in Ajax Communications. The Web development community has developed JSON parsers and serializers for almost all major languages, making it extremely easy to export and use JSON data from the server.
Douglas Crockford also maintains a JSON serializer/parser for JavaScript, which, for http://www.json.org/js.html, can download that JavaScript file, which works in all browsers. In addition, the IE8 contains the native version of the Crockford parser.
In this JSON library of Crockford, there is a global object that has two methods: Parse () and stringify (). where the parse () method accepts two parameters: JSON text and an optional filter function. In the case where the incoming text is a valid JSON, the parse () method returns an object representation of the incoming data. The following is an example of using the Parse () method:
- var object=json.parse ("()");
Unlike the direct use of eval (), there is no need to parenthesis the incoming text.
The second argument is a function that takes a JSON key and a value as a parameter. The function must return a value in order for the key passed in as a parameter to appear in the resulting object. Its return value becomes the value associated with the specified key in the result object, and therefore provides an opportunity for us to override the default parsing mechanism. In other words, returning undefined to a key in this function removes the key from the result object. As shown in the following example:
- var jsontext="{" \name\": \" wanggang\ ", \" age\ ": 29,\" author\ ": true}";
- var object=json.parse (Jsontext,function (key,value) {
- Switch (key) {
- Case ' age ': return value+1;
- Case "Author": return undefined;
- Default: return false;
- }
- });
- Alert (object.age) //30
- Alert (object.author) //undefined
In the above code, the filter function adds 1 to the value of each "age" key, removes the "author" key from the data, and the other values are returned as-is. As a result, the Age property value in the resulting object becomes 30, but there is no author attribute, which is often used to process the data returned by the server. Suppose addressbook.php returns JSON data in the following format:
- {
- {
- "Name":"Wangmeng",
- "Email":"[email protected]"
- },{
- "Name":"Lintao",
- "Email":"[email protected]"
- },{
- "Name":"Jim",
- "Email":"[email protected]"
- }
- }
You can send an AJAX request to get the above data, and then generate the corresponding <ul/> elements using the following code on the client:
- var xhr=createxhr ();
- xhr.onreadystatechange=function () {
- if (xhr.readystate = = 4) {
- if ((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {
- var contacts=json.parse (Xhr.responsetext);
- var List=document.getelementbyid ("Contacts");
- for (var i=0,len=contacts.length;i<len;i++) {
- var li=document.createelement ("Li");
- Li.innerhtml="<a href=\" mailto: "+ contacts[i].email + " \ ">" + contacts[i].name + "</a>";
- List.appendchild (LI);
- }
- }
- Xhr.open ("Get","addressbook.php",true);
- Xhr.send (null);
- }
- };
The above code obtains a JSON string from the server, then parses it into a JavaScript array, and after getting the array, iterating through each of these objects, it is easy to insert the corresponding values into the DOM. Specifically, the,<ul/> element contains some <li/> elements, and each <li/> element contains a link that can be clicked to send an e-mail to one person.
JSON is also the browse format for sending data to the server. When sending data, JSON is generally placed in the post element request body, and the Stringify () method of the JSON object is designed for this purpose. This method takes 3 parameters: the object to serialize, an optional replacement function (to replace an unacceptable JSON value), and an optional indentation specifier (which can be the number of spaces indented at each level, or the character used to indent). By default, Stringify () returns the non-indented JSON string, which is an example:
- var contact={
- Name:"Wangmeng",
- Email:"[email protected]"
- };
- var jsontext=json.stringify (contact);
- alert (Jsontext);
The warning box in this example displays the following non-indented strings:
(\ "name\": \ "wangmeng\", \ "email\": \ "wangmeng\": \[email protected]\)
Since not all javasrcipt values can be represented by JSON, only those values that are officially supported are included in the results. For example, functions and undefined values cannot be represented by JSON, and any keys that contain them will be removed by default. To change this default behavior, you can pass in a function at the position of the second parameter. Whenever an unsupported data type is encountered during serialization, the function is applied in the scope of the object being serialized, and its arguments are the corresponding keys and values.
For JSON-supported data types, this function is not called during serialization, including: String, numeric, Boolean, NULL, object, array, and date. Take a look at the following example:
- var jsontext=json.stringify ([new Function ()],Function (key,value) {
- if (value instanceof Function) {
- return "(function)";
- }else{
- return value;
- }
- });
- alert (Jsontext); //"(function)"
This example attempts to serialize an array that contains a function. When a function value is encountered, the second parameter (that is, the filter function) converts it to a string "(function)", which appears in the final result.
You can send JSON data to the server by using a POST request and passing the JSON text to the Send () method. Take a look at the following example:
- var xhr=createxhr ();
- var contact={
- Name:"Wangmeng",
- Email:"[email protected]"
- };
- xhr.onreadystatechange=function () {
- if (xhr.readystate = = 4) {
- if ((Xhr.status <= && xhr.status <) | | xhr.status = = 304) {
- alert (Xhr.responsetext);
- }
- }
- };
- Xhr.open ("POST","addcontact.php",true);
- Xhr.send (json.stringify (contact));
This example is to save the new contact information to the server, so send the data to the addcontact.php file. After the contact object is built according to the new contacts information, it is serialized into JSON data and passed to the Send () method. The PHP page on the server is responsible for parsing the received JSON data back into its original format so that the server-side code can understand it and also sends a response to the browser.
Talking about the use of JSON in Ajax