如何下载通过post生成的php文件,同时避免页面位置被更改?
I have a file download.php
which I feed via post with data and then generates an svg file to download via setting the header with
header('Content-Type: application/svg+xml');
header("Content-Disposition: attachment; filename=\"myfilename\"");
Now, the question is how to initiate the download. My first attempt was to put the data into a form and submit it via post with
<form id="svgform" method="post" action="download.php" style="display: none;">
...
</form>
Normally, this works fine. It will not change the location to download.php but only initiate the download. Unfortunately, this method seems to have the caveat that (in the rare case) where the php request generates an error (for whatever reason), the page is changed. I want to avoid a page change at all cost (because unsaved data may be lost). It also has some other strange side-effects [1].
So, next I tried to initiate the download in a new tab via
<form id="svgform" method="post" target="_blank" action="download.php" style="display: none;">
...
</form>
This leads to an ugly white page popping up for a moment before the download starts. Even worse, in IE 11 the white page does not close and the download dialog lands on the previous page so the user does not see it immediately.
So, I am wondering what is the best way to go ahead. Could the download be better achieved via AJAX and how?
[1] For some reason, Firefox cannot generate html inspector data when the inspector has been opened before. Here is a way to see what I mean. Inspect some element in Firefox and leave the inspector open. Now, go to a page that downloads data via the method above (or similar), e.g. http://download.cnet.com/CCleaner/3001-18512_4-10315544.html. The inspector becomes empty and no element can be inspected anymore. Furthermore, some of my scripts stopped working properly in IE 11. I am not sure yet why maybe it is related to what happens in Firefox.
Since you don't want to change the URL when posting the form but you still want a download to start, you can post the form an iframe instead.
<form target="my-iframe-id" method="post" ... >
and the iframe:
<iframe id="my-iframe-id" ... ></iframe>
You can set the iframe as display: none;
so it doesn't show.