JAVA SCRIPT - Handling an XML Document Returned via an Ajax Cal

Handling an XML Document Returned via an Ajax Cal


Problem

You need to prepare your Ajax application to deal with data returned in XML. 

Solution

First, ensure the application can handle a document with an XML MIME type:
if (window.XMLHttpRequest) {
 xmlHttpObj = new XMLHttpRequest();
 if (xmlHttpObj.overrideMimeType) {
 xmlHttpObj.overrideMimeType('application/xml');
 }
}

Next, access the returned XML document via the XHMLHttpRequest’s responseXML property, and then use the DOM methods to query the document for data:

if (xmlHttpObj.readyState == 4 && xmlHttpObj.status == 200) {
 var citynodes = xmlHttpObj.responseXML.getElementsByTagName("city");
 ...
}

EXPLAIN

When an Ajax request returns XML, it can be accessed as a document object via the XMLHttpRequest object’s responseXML property. You can then use DOM methods to query the data and process the results.  

If the server-side application is returning XML, it’s important that it return a MIME type of text/xml, or the responseXML property will be null. If you’re unsure whether the API returns the proper MIME type, or if you have no control over the API, you can override the MIME type when you access the XMLHttpRequest object:


if (window.XMLHttpRequest) {
 xmlHttpObj = new XMLHttpRequest();
 if (xmlHttpObj.overrideMimeType) {
 xmlHttpObj.overrideMimeType('application/xml');
 }
}


The overrideMimeType() is not supported with versions of IE older than IE11, nor is it supported in the first draft for the W3C XMLHttpRequest specification.

Because of this uncertain support, if you want to use responseXML, it’s better to either change the server-side application so that it supports the application/xml MIME type, or convert the text into XML using the following cross-browser technique:


if (window.DOMParser) {
 parser=new DOMParser();
 xmlResult = parser.parserFromString(xmlHttpObj.responseText,
 "text/xml");
} else {
 xmlResult = new ActiveXObject("Microsoft.XMLDOM");
 xmlResult.async = "false"
 xmlResult.loadXML(xmlHttpObj.responseText);
}
var stories = xmlResult.getElementsByTagName("story");

Parsing XML in this way adds another level of processing. It’s better, if possible, to return the data formatted as XML from the service.Demonstrates a complete application page processing an XML document.

0 comments:

Post a Comment