2015-08-25 35 views
1

如何評估在獲取api中獲取的http響應(Is there a way to not send cookies when making an XMLHttpRequest on the same origin?)?如何評估在獲取api中收到的http響應

作爲獲取調用的結果,我們可以訪問responseText。現在我們可以通過編程方式(可能通過responseText上的api調用)瀏覽器執行的操作(稱爲頁面加載),如下載圖像,css文件等並評估腳本,並且可能會做出xmlhttprequests(如果有)。

當完成所有這些工作後,我希望得到頁面的html內容,即完成所有這些後,即等同於瀏覽器從「加載」狀態變爲「完成」時。

我希望問題很清楚。

+1

如果您添加了「Javascript」標籤,您是否認爲您可能會從社區獲得更好的回覆? –

+0

yeap。你是對的......)完成。 – jack

+0

@Kkinsey任何答覆我的問題btw? ;) – jack

回答

1

您可以將response.text()渲染爲(如果您願意,可以使用visibility: hidden)。然後你就可以與所有的標準功能,操作新的文檔:

<!DOCTYPE html> 
<html> 

<head> 
    <title>This is the page title</title> 
    <meta charset="UTF-8"> 
    <meta name="description" content="Free Web Help"> 
    <meta name="keywords" content="HTML,CSS,XML,JavaScript"> 
    <meta charset="utf-8"> 
</head> 

<body> 

</body> 

<script> 
    var img = new Image(); 
    img.src = "http://cdn.sstatic.net/stackoverflow/img/[email protected]"; 
    document.body.appendChild(img); 
    fetch("so.html") 
    .then(function(response) { 
     return (response.text()); 
    }) 
    .then(function(responseText) { 
     // limit the recursion depth to 1 
     if (!window.frameElement) { 
     var newDoc = document.createElement('iframe'); 
     document.body.appendChild(newDoc); 
     newDoc.contentDocument.write(responseText); 
     } 
    }); 
</script> 

</html> 

自己試用,您可以將此代碼保存爲so.html,並訪問您的本地Web服務器上,或者你可以check it out here

+0

這太棒了!但問題是使用iframe加載頁面意味着cookies將與http請求一起發送。爲了避免cookie,這就是我首先使用fetch API而不是普通xmlhttprequest的原因。任何可以避免這種情況的替代解決方案。 – jack

+0

我認爲這符合您的使用案例 - 在這裏,我只是將從提取api返回的'response.text()'寫入'