2013-09-25 199 views
1

給定一個包含整個頁面的HTML的字符串,我只需要body的innerHTML。而不是自己解析HTML,如果我可以從字符串中創建一個元素,然後直接獲取主體,似乎更容易。從字符串獲取DOM

我發現了一些相關的東西,但我無法工作(我再也找不到問題了)。

xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange=function() 
{ 
    var ret = xmlhttp.responseText + ""; 

    if(xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
     alert(ret); 
    } 
} 
xmlhttp.open("GET", "http://url.php", false); 
xmlhttp.send(); 

現在我有這個ajax請求,但我只需要從返回的身體。

我試過document.createElement(ret).bodynew Element(ret).body但他們似乎沒有工作。

回答

4
var helper = document.createElement("html"); 
helper.innerHTML = ret;   
body = helper.querySelector("body"); //Or getElementsByTagName("body")[0] 
+0

'ret.body'或'helper.body'? – Cruncher

+0

我在'helper.innerHTML = ret;'出現錯誤。 「無法設置innerHTML屬性,此操作的目標元素無效。」 – Cruncher

+0

@Cruncher謝謝,編輯 –

-1

你可以使用simple_html_dom要做到這一點,並獲得使用PHP整個頁面的HTML,然後得到的只是身體的內容,類似這樣的

$html=file_get_html("url.php"); 
$body=$html->find("body"); 
$echo $body->plaintext