Load and parse XML data using Ajax in 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

  1. Header("Content-Type: text/XML");// PHP
  2. Response.Contenttype="Text/XML" // ASP
  3. Response.Setheader("Contenttype","Text/XML");// JSP

2. XML structure.
XML must be closed. It is very important!
Example:
Incorrect XML

  1. <?XML Version="1.0" Encoding="UTF-8"?>
  2. <Name>Zhangsan</Name>
  3. <ID>1</ID>
  4. <Name>Lisi</Name>
  5. <ID>2</ID>

Correct

  1. <?XML Version="1.0" Encoding="UTF-8"?>
  2. <Stulist>
  3. <Student Email="1@1.com">
  4. <Name>Zhangsan</Name>
  5. <ID>1</ID>
  6. </Student>
  7. <Student Email="2@2.com">
  8. <Name>Lisi</Name>
  9. <ID>2</ID>
  10. </Student>
  11. </Stulist>

3. Parsing
Here, macnie's
Traverse student (here we still use the above XML and the sub-node is student)

  1. $.Ajax({
  2. URL:'Ajax. asp',
  3. Type:'Get',
  4. Datatype:'XML',// Do not write here, but do not write text or HTML !!!
  5. Timeout:1000,
  6. Error:Function(XML){
  7. Alert('Error loading XML document'+XML);
  8. },
  9. Success:Function(XML){
  10. $ ( XML ) . Find ( " Student " ) . Each ( function ( I ) {
  11. var id =$ ( This ) . children ( " id " ) ; // get object
  12. var idvalue =$ ( This ) . children ( " id " ) . text () ; // retrieve text
  13. Alert(Id_value);// Here is the ID value.
  14. Alert($(This).ATTR("Email"));// The email attributes under student are displayed here.
  15. // The final output. This is the CSS rain method, which seems to be a little more JQ than macnie.
  16. $('<Li> </LI>')
  17. .Html(Id_value)
  18. .Appendto('Ol');
  19. });
  20. }
  21. });

The last one is added:Ensure that the server is UTF-8 encoded, otherwise garbled! At the same time, make sure that your xml file is also UTF-8
Format :-)

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.