我正在開發一個鉻擴展,所以我對於我要求的域的XMLHttpRequests擁有跨主機權限。如何通過XMLHttpRequest從html頁面創建DOM對象?
我已經使用了XMLHttpRequest並獲得了一個HTML網頁(txt/html)。我想使用XPath(document.evaluate)從中提取相關的位。不幸的是,我無法從html的返回字符串構造一個DOM對象。
var xhr = new XMLHttpRequest();
var name = escape("Sticks N Stones Cap");
xhr.open("GET", "http://items.jellyneo.net/?go=show_items&name="+name+"&name_type=exact", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xhr.responseText,"text/xml");
console.log(xmlDoc);
}
}
xhr.send();
console.log
將在Chromium JS控制檯中顯示調試內容。
在上述JS控制檯中。我得到這個:
Document
<html>
<body>
<parsererror style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
<h3>This page contains the following errors:</h3>
<div style="font-family:monospace;font-size:12px">error on line 1 at column 60: Space required after the Public Identifier
</div>
<h3>Below is a rendering of the page up to the first error.</h3>
</parsererror>
</body>
</html>
因此,如何是我該使用XMLHttpRequest - >接收HTML - >轉換爲DOM - >使用XPath橫向?
我應該使用「隱藏的」iframe hack來加載/接收DOM對象嗎?
我使用IFRAME技術在我們的web應用程序中加載HTML。它速度很快,即使在IE8上也能正常運行。當你在DOM中時,你可以使用CSS選擇器代替Xpath。 – Mic 2010-10-19 21:44:39
@Mic謝謝。我會盡力解決這個問題。這只是我在做幾頁數據的屏幕截圖,XPath是一個真正的奇蹟=)允許你從任何表格中獲得所有類似的數據。 – Dima 2010-10-19 21:48:40
CSS選擇器是用於HTML的,Xpath是用於XML的,但多一點人力:) – Mic 2010-10-19 22:03:44