7

I'm working on an ajax-enabled page and I need to download files without refreshing the page. In order to do this, I added a hidden iframe on the page.

<iframe id="iframeDownload" style="display:none"></iframe>

When I need to download a file, I use a script like this:

$("#iframeDownload").attr("src","url to server");

On server side, I need to implement some logic and it may return some different http status codes to indicate problems on server side. If the file is downloaded successfully, then it's fine. But in case there is a problem on server side, I need to catch these http codes.

$("#iframeDownload").load(function(e){
    // get http status code and act accordingly but I cannot get it
});

Thanks for any reply.

Update: In my opinion, when we download via iframe, the browser will handle sending requests and receiving responses and only pass the response body to the iframe. Therefore, javascript cannot read response header. This case is similar to loading a page. Please correct me if I'm wrong.

4

2 回答 2

1

忘记 HTTP 状态。Onload事件没有返回任何内容:

document.getElementById("iframeDownload").onload = function(e){console.dir(e);)};

您可以在 iframe 响应中嵌入 javascript:

<html>
    <head>    
    <script>window.parent.loadSucceded()</script>
    </head>
    <body></body>
</html>

这将在您的主页上调用loadSucceded函数,因此您的应用程序会收到有关成功下载的通知。

于 2015-06-26T17:30:52.193 回答
0

我最近遇到了这种情况,我找到了一种处理加载错误的方法。我更改了默认的 Apache 错误页面,以插入一些代码,例如 JS parent.downloaderror_handler('put what you want');

我没有测试它,但也许$_SERVER['HTTP_REFERER']只有在某些情况下你才能测试发送 JS。

请参阅此stackexchange 主题以创建您自己的 500 页面。

于 2014-03-25T15:48:53.563 回答