我不知道您所称的“AJAX JavaScript 库”究竟是什么——发出 HTTP 请求是一个问题与访问文档树中的节点不同。
如果您将库理解为“用于开发软件的资源集合”(Wikipedia),那么,作为 JSX 库的一部分,我为 @987654328 编写了相当兼容的¹包装器@ 和命名空间感知 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>
如果你想从它的res:UNDO_COUNT 元素中提取1.0,你可以这样写:
<!-- 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
¹ JSX:object.js、http.js 和 xpath.js 的组合已在 Gecko、WebCore、MSHTML 和 Opera 浏览器中测试为阳性。然而,JSX 目前主要是实验性代码。
Testcase,见脚本控制台
欢迎提供建设性反馈。另外,JSX 是free software。 (你还不能创建checkout,但我正在努力。)