I do not know exactly what you are calling an "AJAX JavaScript library" – making HTTP requests is a problem different from accessing nodes in a document tree.
If you understand a library as "a collection of resources used to develop software" (Wikipedia), then, as part of the JSX library, I have written rather compatible¹ wrappers for XMLHttpRequest
and namespace-aware DOM Level 3 XPath: http.js
and xpath.js
.
http.js
supports synchronous and asynchronous processing in the same way, and can even access the local filesystem (if permission is granted). Because JSX qualifies as a library then, you can use http.js
and xpath.js
either separately, with foreign code to complement either one, or together.
You would use them together, for example, as follows. Suppose you had an XML document with resource name test.xml
like
<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>
and you wanted to extract the 1.0
from its res:UNDO_COUNT
element, you could write:
<!-- 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>
See also: Parsing XML / RSS from URL using Java Script
¹ A combination of JSX:object.js
, http.js
, and xpath.js
has been tested positive in Gecko-, WebCore-, MSHTML-based and Opera browsers. However, JSX is mostly experimental code for now.
Testcase, see script console
Constructive feedback is welcome. In addition, JSX is free software. (You cannot do a checkout
yet, but I am working on it.)