我需要在JavaScript中加载来自同一站点的另一个页面的变量内容,然后从该内容获取数据(解析XML)。解析XMLHttpRequest()结果(使用XPath)
我已经在文本字符串变量中使用XMLHttpRequest()和responseText属性获取页面的HTML。
之后,我将文本字符串转换为xml对象(DOMParser)并尝试使用XPath。
在FireFox的控制台,我看到错误:
Node cannot be used in a document other than the one in which it was created
我如何转换的XMLHttpRequest()结果放入文档对象使用XPath来处理呢? 我该如何使用document.evaluate和这个对象?有更简单的方法来完成我的任务吗?
textString=file_get_contents('my url');
var parser = new DOMParser();
xml = parser.parseFromString(textString, "text/xml");
list = getI("(//td[contains(text(), 'Total:')])[1]",xml);
// Error: Node cannot be used in a document other than the one in which it was created`enter code here`
// HOW USE getI function here? (document.evaluate)
function file_get_contents(url) { // Reads entire file into a string
//
// + original by: Legaev Andrey
// % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
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');
req.open("GET", url, false);
req.send();
return req.responseText;
}
function getI(xpath,elem){return document.evaluate(xpath,(!elem?document:elem),null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);}
上使用'evaluate'方法你的'xml'文件 - 也就是'xml.evaluate(xpath,...' –