Home > Backend Development > XML/RSS Tutorial > Detailed introduction to the sample code of JavaScript parsing JSON and XML

Detailed introduction to the sample code of JavaScript parsing JSON and XML

黄舟
Release: 2017-03-09 16:46:38
Original
1389 people have browsed it

When writing AJAX, you often need to parse a string of characters returned from the server. Here is a brief introduction to the two formats of characters returned by the server and how JS parses them.

1. JSON

  That is, JS Object Notation (JavaScript Object Notation), which is a string of strings combined in the way of declaring objects in JS.
JS can define objects in the following way:

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


This defines the object obj, which has two public attributes id and name. Its attribute value can be directly accessed using obj.id.

When getting data from the server, there is often more than one object, which requires the use of an object array. The object array in JS can be defined with [], as follows:

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


This defines the object array objs, which contains two objects and can be accessed by index. For example, objs[0] will refer to the first object.
At this point you may have thought about the format of the string returned by the server, but a string is a string after all, and we need to convert it into a variable that can be manipulated by JS.
 This uses the eval function, please see the following example:

 
var
 objs 
=
 eval(
"
[{ id: 1, name: 'n_1' }, { id: 2, name: 'n_2'}]
"
);
        alert(objs[
0
].id); 
//
 return 1
Copy after login


 Okay, on the server side, you only need to use the format: [{ id : 1, name: 'n_1' }, { id: 2, name: 'n_2'}] Returns a string,
On the client side, you can use eval() to execute the returned string and obtain an object array.

The following is a simple example using AJAX. Create a new website and add a general handler (GetJson.ashx) in the root directory. The code is as follows:


Detailed introduction to the sample code of JavaScript parsing JSON and XMLDetailed introduction to the sample code of JavaScript parsing JSON and XMLGetJson.ashx
<%@ 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;
}
}

}

在Default.aspx 文件中添加测试脚本:

    
<
script type
=
"
text/javascript
"
>
        
function
 getJson() {
            
//
 在IE7下测试通过,IE6下必须创建 new ActiveXObject("MSXML2.XMLHTTP.6.0")
            
var
 request 
=
 
new
 XMLHttpRequest();
            request.open(
&#39;
GET
&#39;
, 
&#39;
GetJson.ashx
&#39;
);
            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);
//
 &#39;n_2&#39;
                }
            }
            request.send(
null
);
        }
    
<
/
script>
Copy after login

再添加一个测试按钮即可以看到效果:

<input type="button" value="GetJson" onclick="getJson();" />
Copy after login

  二、XML

    JS对XML的解析是基于DOM的,对HTML的DOM熟悉的话,解析XML就没什么困难了。

    注意:在Firefox中,解析器不会忽略空格,所以元素间的空格,FF一样会认为是一个节点。
    不过在我们用程序拼接XML的时候,一般不会出现节点间有空格的情况。

    在根目录下添加一个新的一般处理程序(GetXml.ashx),代码如下:

    在Default.aspx页面添加以下脚本:

      
function
 getXml() {
            
//
 在IE7下测试通过,IE6下必须创建 new ActiveXObject("MSXML2.XMLHTTP.6.0")
            
var
 request 
=
 
new
 XMLHttpRequest();
            request.open(
&#39;
GET
&#39;
, 
&#39;
GetXml.ashx
&#39;
);
            request.onreadystatechange 
=
 
function
() {
                
if
 (request.readyState 
==
 
4
 
&&
 request.status 
==
 
200
) {
                    
var
 xmlDoc 
=
 request.responseXML;
                    
var
 root 
=
 xmlDoc.documentElement;
                    
var
 elements 
=
 root.getElementsByTagName(
"
Person
"
);
                    alert(elements.length); 
//
 2
                    
//
 elements[0].firstChild 引用到第一个Person节点的Id节点
                    
//
 elements[0].firstChild.firstChild 引用到Id节点的文本节点
                    
//
 因为文本节点是元素节点的第一个子节点
                    alert(elements[
0
].firstChild.firstChild.nodeValue); 
//
 1
                    alert(elements[
1
].lastChild.firstChild.nodeValue);  
//
 &#39;n_2&#39;
                }
            }
            request.send(
null
);
        }
Copy after login


    注意到代码段:var root = xmlDoc.documentElement;

    主要是为了消除IE6和其他浏览器的兼容问题,在其他浏览器下,允许request.responseXML.getElementsByTagName("Person");

    添加测试按钮:

<input type="button" value="GetXml" onclick="getXml();" />
Copy after login

 

总结:从代码上很容易看出,解析JSON相对直观,在网络中需要传输的字符串也比较少,解析过程中也不需要考虑浏览器兼容问题。
     但JSON比较适合轻量级的数据交互,XML则比JSON多了一些特性,比如命名空间,还有更多的节点类型。


The above is the detailed content of Detailed introduction to the sample code of JavaScript parsing JSON and XML. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template