Talking about the use of JSON in Ajax

Source: Internet
Author: User
Tags php language serialization javascript array

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:

    1. 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:

  1. var jsontext="{" \name\": \" wanggang\ ", \" age\ ": 29,\" author\ ": true}";
  2. var object=json.parse (Jsontext,function (key,value) {
  3. Switch (key) {
  4. Case ' age ': return value+1;
  5. Case "Author": return undefined;
  6. Default: return false;
  7. }
  8. });
  9. Alert (object.age) //30
  10. 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:

    1. {
    2. {
    3. "Name":"Wangmeng",
    4. "Email":"[email protected]"
    5. },{
    6. "Name":"Lintao",
    7. "Email":"[email protected]"
    8. },{
    9. "Name":"Jim",
    10. "Email":"[email protected]"
    11. }
    12. }

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:

  1. var xhr=createxhr ();
  2. xhr.onreadystatechange=function () {
  3. if (xhr.readystate = = 4) {
  4. if ((Xhr.status >= && xhr.status <) | | xhr.status = = 304) {
  5. var contacts=json.parse (Xhr.responsetext);
  6. var List=document.getelementbyid ("Contacts");
  7. for (var i=0,len=contacts.length;i<len;i++) {
  8. var li=document.createelement ("Li");
  9. Li.innerhtml="<a href=\" mailto: "+ contacts[i].email + " \ ">" + contacts[i].name + "</a>";
  10. List.appendchild (LI);
  11. }
  12. }
  13. Xhr.open ("Get","addressbook.php",true);
  14. Xhr.send (null);
  15. }
  16. };

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:

    1. var contact={
    2. Name:"Wangmeng",
    3. Email:"[email protected]"
    4. };
    5. var jsontext=json.stringify (contact);
    6. 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:

    1. var jsontext=json.stringify ([new Function ()],Function (key,value) {
    2. if (value instanceof Function) {
    3. return "(function)";
    4. }else{
    5. return value;
    6. }
    7. });
    8. 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:

  1. var xhr=createxhr ();
  2. var contact={
  3. Name:"Wangmeng",
  4. Email:"[email protected]"
  5. };
  6. xhr.onreadystatechange=function () {
  7. if (xhr.readystate = = 4) {
  8. if ((Xhr.status <= && xhr.status <) | | xhr.status = = 304) {
  9. alert (Xhr.responsetext);
  10. }
  11. }
  12. };
  13. Xhr.open ("POST","addcontact.php",true);
  14. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.