Reputation: 3700
I am looking at a scenario where I want to "consume" an xml/json document and build some visual elements from said date.
Per example, List of bookings for a time period. Lets say data will contain
<unit>
<booked>
<pic>
<booked range>
What I am not sure of, is how to go from accessing a query string, to catching the returned xml. This seems simple, but I cant seem get get my head around accessing the XML returned, from Javascript.
More info:
I am building a mobile app, that will display data, retrieved from XML. (I want to run the url/query string from the app, to generate a custom xml doc, and read XML data returned (not display the web page)
Any advice?
Upvotes: 0
Views: 66
Reputation: 17238
Synopsis
Code
A pure Javscript solution using the XMLHttpRequest ( docs: eg. MDN reference, MDN usage hints; there also exists a tutorial on html5rocks ) might look similar to the following fragment:
var oReq = new XMLHttpRequest();
function eh_onload ( ) {
var xmlhttp = this;
if (xmlhttp.readyState === 4) {
console.log ( "xmlhttp.status = " + xmlhttp.status);
if (xmlhttp.status === 200) {
//
// process your xml here.
//
console.log ( "responseText = '" + xmlhttp.responseText + "'");
console.log ( "xml root element = '" + xmlhttp.responseXML.documentElement.nodeName + "'");
}
else {
console.log('error');
}
}
}
oReq.onload = eh_onload;
oReq.open("get", "http://wsearch.nlm.nih.gov/ws/query?db=digitalCollections&term=cholera", true);
oReq.send();
The code snippet performs an ajax request and registers a callback that will be executed upon completion of the request. As you can see, you may either access the lexical representation of the xml data received or a parsed DOM structure.
Alternative
In case using the jquery library is acceptable to you, you may proceed along the lines of the following code sample:
function eh_xml ( parsedxml, textStatus, jqXHR ) {
// process your xml here.
//
console.log ( "typeof(parsedxml) = '" + typeof(parsedxml)+ "'");
console.log ( "$('term', parsedxml).length = " + $("term", parsedxml).length);
}
$.ajax({
url: "http://wsearch.nlm.nih.gov/ws/query?db=digitalCollections&term=cholera"
, dataType: "xml"
, success: eh_xml
});
The code snippet performs an ajax request and provides a callback that receives the xml in parsed (DOM) representation.
Note & Caveat
The code sample uses a public web service provided by the US NIH returning xml data. This one has been selected randomly and is employed for the sole purpose to have a working PoC. No affiliations exist and the usual legal disclaimers apply.
The code can be tested from the console (eg. in Chrome) opened on the site http://wsearch.nlm.nih.gov/ using the following prelude which loads the jquery library in the context of the site hosting the web service:
var script = document.createElement("script");
script.src = "http://code.jquery.com/jquery-2.1.3.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
Upvotes: 1