2015-08-25 34 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()'写入'