简体   繁体   中英

Examples using javascript to run a GET on another URL, retrieve the xml returned and look up a specific node?

如何从javascript中的特定网址获取xml文档,然后查找特定的子节点并获取值?

You can use XMLHttpRequest to make an AJAX call to the url, as long as it's on the same domain (AJAX has same-origin policy). Also, take a look here for some tips on manipulating XML in Javascript.

If you are using jQuery, you can use jQuery.ajax and set the datatype to XML .

If your XML resides on another URL (ie, not on your domain), then things get trickier. You'll need to use something server-side (like PHP, ASP, or JSP's) that generates a Javascript file that contains the XML (which it grabs from the URL) stored in a string. Then, in your page you'll need a script tag that points to this Javascript file.

Using jQuery it's really easy because you an 'query' the XML document like you would with an X/HTML document.

Let's say you had a simple xml document like this...

<book>
  <title>Catcher in the Rye</title>
  <author>J.D. Salinger</author>
</book>

You can use jQuery to load the document and parse out particular nodes.

<html>
<head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
  <script type="text/javascript">
    $(function() {
        $.get("/book.xml", function(responseXml) {
            var xml = $(responseXml);
            var title = $("title", xml).text();
            var author = $("author", xml).text();

            alert(title); // >> Catcher in the Rye
            alert(author); // >> J.D. Salinger
        });
    });
  </script>
</head>
<body>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM