我正在寻找支持命名空间xml的AJAX JavaScript库。
我在网上阅读了几十篇帖子(包括在stackoverflow上),但没有找到一个好的答案。有许多AJAX示例,但只要命名空间发挥作用就会中断(例如jQuery选择器就是这种情况)。
答案 0 :(得分:0)
我不确切地知道您所谓的“AJAX JavaScript库” - 使HTTP请求与访问文档树中的节点的不同存在问题。
如果您将库理解为“用于开发软件的资源集合”(Wikipedia),那么,作为 JSX 库的一部分,我已编写了相当兼容的¹包装器XMLHttpRequest
和名称空间感知DOM Level 3 XPath:http.js
和xpath.js
。
http.js
以相同的方式支持同步和异步处理,甚至可以访问本地文件系统(如果授予了权限)。因为JSX有资格作为库,所以您可以单独使用http.js
和xpath.js
,使用外部代码来补充任何一个或一起。
您可以将它们一起使用,例如,如下所示。假设您有一个资源名称为test.xml
的XML文档,如
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<res:Response
xmlns:res="http://domain.example/Response">
<res:OUTPUT>
<res:UNDO_COUNT>1.0</res:UNDO_COUNT>
<res:MSG>Undo complete (No more to undo)</res:MSG>
</res:OUTPUT>
</res:Response>
<res:OUTPUT
xmlns:res="http://domain.example/Response">
foo
</res:OUTPUT>
</soap:Body>
</soap:Envelope>
你想从1.0
元素中提取res:UNDO_COUNT
,你可以写:
<!-- 1. Include prerequisites and dependencies using Resource Builder (recommended) -->
<script type="text/javascript" src="builder.php?src=object,string,http,xpath"></script>
<script type="text/javascript">
/*
* 2. Construct the HTTP request wrapper;
* the default is a GET request with asynchronous handling
*/
var request = new jsx.net.http.Request("test.xml");
/* 3. Prepare processing of the HTTP response */
request.setSuccessListener(function (response) {
/* 5. Get the reference to the XMLDocument object */
var doc = response.responseXML;
/* 6. Create the namespace resolver that fits your query best */
var nsResolver = jsx.xpath.createFullNSResolver(null, doc);
/* 7. Make the XPath query */
var nodes = jsx.xpath.evaluate("//res:UNDO_COUNT/text()", doc, nsResolver);
/*
* 8. Process the result. jsx.xpath.evaluate() returns a reference
* to an Array instance if you do not specify the result type.
*/
/* "1.0" */
console.log(nodes[0].data);
});
/* 4. Make the HTTP request */
request.send();
</script>
另请参阅:Parsing XML / RSS from URL using Java Script
¹在Gecko,WebCore,MSHTML和Opera浏览器中,JSX:object.js
,http.js
和xpath.js
的组合已经过测试。但是,JSX现在主要是实验代码。
Testcase,请参阅脚本控制台
欢迎提供建设性的反馈意见。此外,JSX是free software。 (你还不能做checkout
,但我正在努力。)