Parsing XMLHttpRequest() result (using XPath)

白昼怎懂夜的黑 提交于 2019-12-04 20:03:08

There was some moments in this task:

  • Property responseXML has been equal null (in FireFox) without using req.overrideMimeType. After I start using req.overrideMimeType- property responseXML isn't null already, but I couldn't correctly use XPath still. Thus I used responseText property and DOMParser;
  • When we use document.evaluate method we should use it on HTMLDocument object that was created, not for main document object;
  • There are Cyrillic symbols on loaded page, so I should get result in the charset windows-1251 to use XPath properly

Final result is:

req = new XMLHttpRequest();
req.open("GET", 'http://my_url', false);
req.overrideMimeType('text/xml; charset=windows-1251'); // for Cyrillic
req.send(null);

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(req.responseText, "text/html"); 

var list = xmlDoc.evaluate("(//td[contains(text(), 'Total (Всего):')])[1]",xmlDoc,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
if(list.snapshotLength>0){
// operations
}

First, all this:

var req = null;
try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
    try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
        try { req = new XMLHttpRequest(); } catch(e) {}
    }
}
if (req == null) throw new Error('XMLHttpRequest not supported');

Can be replaced with just this:

var req = new XMLHttpRequest();

Because every browser has implemented a native XMLHttpRequest object for quite some time.

Second, when you get your response, look for it in the responseXML (responseXML) property of the XHR NOT the responseText property. This will return a Document object containing the nodes of the XML response which you can then parse using the Core DOM or an XML Parser if you like. But since you are using the responseText property at the moment, your DOM Parser is choking on it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!