简体   繁体   English

如何与content-disposition:附件暂时停用onbeforeun-message?

[英]How to temporally deactivate onbeforeunload-message in combination with content-disposition: attachment?

I have one page insert.php where the user can make inputs into a form. 我有一个页面insert.php ,用户可以在其中输入表单。

I use javascript to inform the user about possible loss of inserted data when the page is closed. 当页面关闭时,我使用javascript通知用户有关插入数据可能丢失的信息。

<script language="JavaScript">
    var needToConfirm = true;

    window.onbeforeunload = confirmExit;

    function confirmExit() {
        if ( needToConfirm )
        return "This page is asking you to confirm that you want to leave - data you have entered may not be saved.";
    }
</script>

Then I have a form that contains an element to download ("save") the data inserted. 然后,我有一个包含要下载(“保存”)所插入数据的元素的表单。

<form action='insert.php' method='post'>
    ... other input elemets ...
    <input type="submit" name="save" value="Save" onclick="needToConfirm = false;">
</form>

When this save-button is pressed, no data is lost, since the form just reloads itself and refills the form with the $_POST -data. 按下此保存按钮后,不会丢失任何数据,因为该表单会自动重新加载并使用$_POST -data $_POST该表单。 Hence I set the needToConfirm variable to false to not make the user worried. 因此,我将needToConfirm变量设置为false以使用户不必担心。

Furthermore, the $_POST -data is downloaded when reloading the page ( insert.php ) using: 此外,使用以下方法重新加载页面( insert.php )时,将下载$_POST -data:

session_start();
... store $_POST in $_SESSION ...
Header( 'HTTP/1.1 301 Moved Permanently');
Header($'Location: save.php');

Where in save.php I do this: save.php我这样做:

session_start();
header( 'Content-disposition: attachment; filename=download.dat' );
... echo $_SESSION-data ...

This downloads the inserted data without closing the already loaded insert.php . 这将下载插入的数据,而不会关闭已经加载的insert.php

The problem is that the javascript needToConfirm -variable stays on false . 问题是javascript needToConfirm保持为false Hence when I close the page after clicking on download (even if the download was not confirmed by the user) no warning is shown anymore and data may be lost. 因此,当我单击下载后关闭页面时(即使用户未确认下载),也不再显示警告,并且数据可能会丢失。

Any ideas how to solve this problem are very appreciated. 任何解决此问题的想法都将受到赞赏。

(I guess the problem is related to the insert.php somehow not fully reloaded due to the loading of the other page...) (我想这个问题与insert.php有关,由于加载了其他页面, insert.php以某种方式未完全重新加载...)

you would need to set up a timer and after some timeout, reset the value again to true (you should not have to use bigger then 100ms) 您将需要设置一个计时器,并在超时后将其重新设置为true(您不必使用大于100ms的值)

window.setTimeout('needToConfirm=true', 100);

Put that into the onclick so when there is content to show, the page reloads itself, but when there is just the attachment, the timer fires 将其放入onclick中,以便在有要显示的内容时,页面会自动重新加载,但只有附件时,计时器才会触发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM