Parse JSON and XML using J2EE JS

Source: Internet
Author: User

When writing Ajax, it is often necessary to parse a string returned from the server. Here we will briefly introduce two formats of characters returned by the server and the parsing methods of Js for them.

I. JSON

JavaScript Object Notation (JavaScript Object Notation) is a string that is combined by declaring objects in Js.
JS can define objects as follows:

VaR OBJ =
{
ID: 2,
Name: 'n'
};

In this way, the object obj is defined. It has two common attributes: ID and name. You can directly access its attribute values using obj. Id.

When obtaining data from the server, there is usually more than one object, which requires an array of objects. The array of objects in JS can be defined using [], as shown below:

VaR objs = [{ID: 1, name: 'n' _ 1'}, {ID: 2, name: 'n' _ 2'}];
Alert (objs [0]. ID );

In this way, the object array objs is defined. It contains two objects and can be accessed using indexes. For example, objs [0] Will reference the first object.
Here you may have thought about the format of the string returned by the server, but the string is a string after all, and we need to convert it to a variable that can be operated by Js.
This uses the eval function. See the following example:

VaR objs = eval ("[{ID: 1, name: 'n' _ 1'}, {ID: 2, name: 'n' _ 2'}]");
Alert (objs [0]. ID); // return 1 is good. on the server side, you only need to use the format: [{ID: 1, name: 'n' _ 1'}, {ID: 2, Name: 'n' _ 2'}] returns a string,
The client can use eval () to execute the returned string to obtain the object array. The following is a simple example using Ajax. Create a website and add a general handler (getjson. ashx) to the root directory. The Code is as follows: getjson. ashx

Add the test script to the default. aspx file:

<SCRIPT type = "text/JavaScript">
Function getjson (){
// Test passed in IE7. New activexobject ("msxml2.xmlhttp. 6.0") must be created in IE6 ")
VaR request = new XMLHttpRequest ();

Request. Open ('get', 'getjson. ashx ');
Request. onreadystatechange = function (){
If (request. readystate = 4 & request. Status = 200 ){
VaR objs = eval (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 view the effect:

<Input type = "button" value = "getjson" onclick = "getjson ();"/> 2. xml JS parses XML based on Dom, if you are familiar with HTML Dom, it is no longer difficult to parse XML. Note: In Firefox, the parser does not ignore spaces, so spaces between elements are considered as a node like ff.
However, when we splice XML with a program, there is usually no space between nodes. Add a new general handler (getxml. ashx) to the root directory. The Code is as follows: getxml. ashx

Add the following script on the default. aspx page:

Function getxml (){
// Test passed in IE7. New activexobject ("msxml2.xmlhttp. 6.0") must be created in IE6 ")
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.doc umentelement;
VaR elements = root. getelementsbytagname ("person ");
Alert (elements. Length); // 2
// Elements [0]. firstchild references the ID node of the first person Node
// Elements [0]. firstchild. firstchild references the text node of the ID node.
// Because the text node is the first child node of the Element Node
Alert (elements [0]. firstchild. firstchild. nodevalue); // 1
Alert (elements [1]. lastchild. firstchild. nodevalue); // 'N _ 2'
}
}
Request. Send (null );
}

Notice the code snippet: var root = xmldoc.doc umentelement; mainly used to eliminate the compatibility problem between IE6 and other browsers. In other browsers, the request is allowed. responsexml. getelementsbytagname ("person"); Add the test button: <input type = "button" value = "getxml" onclick = "getxml ();"/> conclusion: from the code, it is easy to see that JSON Parsing is relatively intuitive, and there are few strings to be transmitted in the network. browser compatibility is not required during parsing.
JSON is more suitable for lightweight data interaction. XML has more features than JSON, such as namespaces and more node types.

Address: http://www.cnblogs.com/lucas/archive/2009/04/13/1434566.html

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.