My question is totally focussed on Microsoft (Trident) browsers. What is the difference between the reponseXML and loadXML ? Following two codes are shown:
way 1:
var xmlObj = new ActiveXObject("Msxml2.DOMDocument");
xmlObj.async = false;
xmlObj.load('/files/xml/books.xml');
way 2:
var request = new ActiveXObject("Microsoft.XMLHTTP");
request.open("GET", "files/xml/books.xml", false);
request.onreadystatechange = function() { var xmlObj = request.responseXML; };
request.send(null);
In the above snippets, the variable xmlObj in both cases are xml documents. But is there any difference between them ? Because I was trying to do something without ajax calls,
by using the previous snippet but it didn’t work although the xmlObj had the xml file’s content as expected. Kindly help. Thanks.
EDIT :
I found a difference. Let us consider books.xml is:
<books>
<book>
<a/><b/>
</book>
<book>
<a/><b/>
</book>
</books>
Now xmlObj.getElementsByTagName(‘a’).length will return 2 for the second method (ajax call) and it will return 0 for the first method.
The only difference you may encounter between using those two APIs is the version of MSXML you’re dealing with as you’re specifying MSXML2 in one case but not in the other. In general you shouldn’t see any noticeable effects unless you’re doing a lot of XPath or XSLT.
As for those particular code snippets, however, they are quite different. Although you’re specifying that the
send()executes synchronously in way 2 theonreadystatechangedevent will fire several times so you should also check for arequest.readyState == 4before grabbing theresponseXML.That said, because it’s synchronous you don’t need to use
onreadystatechangedat all assend()will only return once the request completes so you could then just grabrequest.responseXMLon the following line.I should also mention, since you talked about invalid XML, that the error case in both methods is the same. Neither will throw an exception for invalid XML – you will get a non-zero
xmlObj.parseError.errorCodevalue instead.