我需要在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,...' –