JavaScript and XML parsing JSON

Writing AJAX, it often needs to resolve a string of a string returned from the server, the server returns the character here briefly two formats, and JavaScript parsing methods on them.

  A, JSON

    I.e., JS object tag (JavaScript Object Notation), is a series of character string objects declared in the manner JS combination.
    JS objects can be defined as follows:

var obj =
    {
        id: 2,
        name: 'n'
    };    

    This defines the object obj, which has two common attribute id and name, attribute values ​​which can be accessed directly obj.id manner.

    Often more than one object from a data acquisition server, which requires use of the object array, the array of objects may be JS [] is defined as follows:

         var  objs  =  [{ id:  1 , name:  ' n_1 '  }, { id:  2 , name:  ' n_2 ' }];
        alert(objs[
0 ].id);

    This defines OBJS array of objects, two objects it contains can be accessed with an index, such as objs [0] to a reference to the first object.
    Here you might have thought the server returns the string format is what, after all, but the string is a string, we need to convert it to a variable can take advantage of JS operations.
    This use eval function, see the following example:

         var  objs  =  eval_r( " [{ id: 1, name: 'n_1' }, { id: 2, name: 'n_2'}] " );
        alert(objs[
0 ].id);  //  return 1
    Well, you just server in the format: [{id: 1, name : 'n_1'}, {id: 2, name: 'n_2'}] Returns a string,
    the client can use eval_r () returns the execution string, get an array.
    The following make a simple example using AJAX. A new site, adding a general processing procedure (GetJson.ashx) in the root directory, as follows:
<%@ WebHandler Language="C#" Class="GetJson" %>

using System;
using System.Web;

public class GetJson : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        string str = "[{id:1, name:'n_1'}, {id:2, name:'n_2'}]";
        
        context.Response.ContentType = "text/plain";
        context.Response.Write(str);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

 

Add the test script in the Default.aspx file:

    <script type="text/javascript">
        function getJson() {
            // 在IE7下测试通过,IE6下必须创建 new ActiveXObject("MSXML2.XMLHTTP.6.0")
            var request = new XMLHttpRequest();

            request.open('GET', 'GetJson.ashx');
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    var objs = eval_r(request.responseText);
                    alert(objs.length); // 2
                    alert(objs[0].id);  // 1
                    alert(objs[1].name);// 'n_2'
                }
            }
            request.send(null);
        }
    </script>

Add a test button to see the results:

< input  type ="button"  value ="GetJson"  onclick ="getJson();"   />
 
  Two, XML
    JS parsing of XML is based on the DOM of the HTML DOM familiar, XML parsing nothing difficult.
    Note: In Firefox, the parser does not ignore spaces, so the space between the elements, FF will be considered as a node.
    But in our program when splicing XML, generally do not have spaces between the nodes happens.
 
    Add a new general handler (GetXml.ashx) in the root directory, as follows:
<%@ WebHandler Language="C#" Class="GetXml" %>

using System;
using System.Web;

public class GetXml : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {

        System.Text.StringBuilder sb = new System.Text.StringBuilder("<?xml version='1.0' ?><Persons>");
        string temp = "<Person><Id>{0}</Id><Name>{1}</Name></Person>";
        sb.AppendFormat(temp, 1, "n_1");
        sb.AppendFormat(temp, 2, "n_2");
        sb.Append("</Persons>");
        
        context.Response.ContentType = "text/xml";
        context.Response.Write(sb.ToString());
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
    Add the following script page in Default.aspx:
        function getXml() {
            // 在IE7下测试通过,IE6下必须创建 new ActiveXObject("MSXML2.XMLHTTP.6.0")
            var request = new XMLHttpRequest();

            request.open('GET', 'GetXml.ashx');
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {
                    var xmlDoc = request.responseXML;
                    var root = xmlDoc.documentElement;
                    var elements = root.getElementsByTagName_r("Person");
                    Alert (elements.length); // 2 
                    // Elements [0] Id .firstChild reference node to the first node of a Person 
                    // Elements [0] .firstChild.firstChild reference text node to node Id 
                    // because text node It is the first child element node 
                    Alert (elements [0] .firstChild.firstChild.nodeValue); // . 1 
                    Alert (elements [. 1] .lastChild.firstChild.nodeValue);   // 'and n_2' 
                } 
            } 
            request.send ( null ); 
        }

 

    Noting snippet: var  the root  =  xmlDoc.documentElement;
    Mainly to eliminate IE6 compatibility problems with other browsers in other browsers, allows request.responseXML.getElementsByTagName_r ( " the Person " );
    Add the test button:
<input type="button" value="GetXml" onclick="getXml();" />
 
 
Summary: It is easy to see from the code parsing JSON relatively straightforward, the string to be transmitted in the network is relatively small, it does not need to be considered during parsing browser compatibility problems.
     JSON but more suitable for lightweight data exchange, XML is much more than JSON some features, such as namespaces, there are many more node types.

Reproduced in: https: //www.cnblogs.com/JoannaQ/archive/2012/09/07/2674501.html

Guess you like

Origin blog.csdn.net/weixin_34303897/article/details/93058216