


Detailed introduction to the sample code of JavaScript parsing JSON and XML
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 ' };
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);
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
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:
GetJson.ashx
在Default.aspx 文件中添加测试脚本:
< 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(request.responseText); alert(objs.length); // 2 alert(objs[ 0 ].id); // 1 alert(objs[ 1 ].name); // 'n_2' } } request.send( null ); } < / script>
再添加一个测试按钮即可以看到效果:
<input type="button" value="GetJson" onclick="getJson();" />
二、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( ' 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( " 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); // 'n_2' } } request.send( null ); }
注意到代码段:var root = xmlDoc.documentElement;
主要是为了消除IE6和其他浏览器的兼容问题,在其他浏览器下,允许request.responseXML.getElementsByTagName("Person");
添加测试按钮:
<input type="button" value="GetXml" onclick="getXml();" />
总结:从代码上很容易看出,解析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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Introduction XML (Extensible Markup Language) is a popular format for storing and transmitting data. Parsing XML in Java is a necessary task for many applications, from data exchange to document processing. To parse XML efficiently, developers can use various Java libraries. This article will compare some of the most popular XML parsing libraries, focusing on their features, functionality, and performance to help developers make an informed choice. DOM (Document Object Model) parsing library JavaXMLDOMAPI: a standard DOM implementation provided by Oracle. It provides an object model that allows developers to access and manipulate XML documents. DocumentBuilderFactoryfactory=D
