[英]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). 您可以使用
XMLHttpRequest
对该URL进行AJAX调用,只要该URL在同一域中(AJAX具有同源策略)。 Also, take a look here for some tips on manipulating XML in Javascript. 另外,在这里看看有关在Javascript中操作XML的一些技巧。
If you are using jQuery, you can use jQuery.ajax
and set the datatype to XML
. 如果使用的是jQuery,则可以使用
jQuery.ajax
并将数据类型设置为XML
。
If your XML resides on another URL (ie, not on your domain), then things get trickier. 如果您的XML驻留在另一个URL上(即不在您的域上),那么事情将变得更加棘手。 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.
您需要使用服务器端(例如PHP,ASP或JSP)来生成Javascript文件,该Javascript文件包含存储在字符串中的XML(XML从URL抓取)。 Then, in your page you'll need a script tag that points to this Javascript file.
然后,在页面中,您将需要一个指向该Javascript文件的脚本标签。
Using jQuery it's really easy because you an 'query' the XML document like you would with an X/HTML document. 使用jQuery非常简单,因为您可以像使用X / HTML文档一样“查询” XML文档。
Let's say you had a simple xml document like this... 假设您有一个像这样的简单xml文档...
<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. 您可以使用jQuery加载文档并解析出特定的节点。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.