問題描述
我需要在 JavaScript 中從同一站點加載另一個頁面的可變內容,然后從該內容中獲取數據(解析 XML).
I need in JavaScript to load in variable contents of another page from the same site and then get data from that contents (parse XML).
我已經使用 XMLHttpRequest() 和 responseText 屬性在文本字符串變量中獲取了頁面的 HTML.
I have gotten in text string variable the page's HTML using XMLHttpRequest() and responseText property.
之后,我將文本字符串轉換為 xml 對象(DOMParser)并嘗試使用 XPath.
After that I converted text string into xml object (DOMParser) and tried to use XPath.
在 FireFox 的控制臺中我看到了錯誤:
In FireFox's console I saw error:
節點不能在它所在的文檔之外的文檔中使用已創建
Node cannot be used in a document other than the one in which it was created
如何將 XMLHttpRequest() 結果轉換為文檔對象以使用 XPath 對其進行處理?我應該如何使用 document.evaluate 和這個對象?有沒有更簡單的方法來完成我的任務?
How can I convert XMLHttpRequest() result into document object to process it using XPath? How I should use document.evaluate with this object? Is there the easier way to do my task?
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);}
推薦答案
在這個任務中有一些時刻:
There was some moments in this task:
- 在不使用 req.overrideMimeType 的情況下,屬性 responseXML 已等于 null(在 FireFox 中).在我開始使用 req.overrideMimeType-property responseXML is not null 之后,我仍然無法正確使用 XPath.因此我使用了 responseText 屬性和 DOMParser;
- 當我們使用 document.evaluate方法我們應該在創建的 HTMLDocument 對象上使用它,而不是用于主文檔對象;
- 加載時有西里爾字母頁面,所以我應該在 charset windows-1251 中得到結果以正確使用 XPath
最終結果是:
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
}
這篇關于解析 XMLHttpRequest() 結果(使用 XPath)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!