AJAX-based XML loading and parsing scripts using JQuery

Source: Internet
Author: User

1, Content-Type
In many cases, the Content-Type issue cannot be resolved.
Skip this step if it is an xml file.
The dynamically generated XML must be set to text/xml. Otherwise, text/html is the common text by default.
Set Content-Type in common languages Copy codeThe Code is as follows: header ("Content-Type: text/xml"); // php
Response. ContentType = "text/xml" // asp
Response. setHeader ("ContentType", "text/xml"); // jsp

2. xml structure.
<Xml must be closed>
Example:
Incorrect XMLCopy codeThe CODE is as follows: CODE:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Name> zhangsan </name>
<Id> 1 </id>
<Name> lisi </name>
<Id> 2 </id>
Correct
CODE:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Stulist>
<Student email = "1@1.com">
<Name> zhangsan </name>
<Id> 1 </id>
</Student>
<Student email = "2@2.com">
<Name> lisi </name>
<Id> 2 </id>
</Student>
</Stulist>

3. Parsing
Here, macnie's
Traverse student (here we still use the above XML and the sub-node is student)Copy codeThe Code is as follows: $. ajax ({
Url: 'ajax. asp ',
Type: 'get ',
DataType: 'xml', // do not write text or html here !!!
Timeout: 1000,
Error: function (xml ){
Alert ('error loading XML document '+ xml );
},
Success: function (xml ){
$ (Xml). find ("student"). each (function (I ){
Var id = $ (this). children ("id"); // retrieves an object
Var id_value = $ (this). children ("id"). text (); // get text
Alert (id_value); // here is the ID value.
Alert ($ (this). attr ("email"); // The email attributes under student are displayed here.
// The final output. This is the CSS rain method, which seems to be a little more JQ than macnie.
$ ('<Li> </li> ')
. Html (id_value)
. AppendTo ('ol ');
});
}
});

Last added: ensure that the server side is UTF-8 encoded.

Related Article

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.