上下文是这样的:
使用下面的代码,将创建文件并显示页面的其余部分,但不会开始下载。此外,如果我点击链接,下载不会启动,但txt文件在浏览器中打开(我想强制下载)。
另一方面,如果我评论javascript并取消注释标题指令,我刷新正确的页面并下载txt文件,但该文件的内容是错误的(它包含在其余部分中回显的html代码)页)。
=================不工作代码==================
echo "
<form name=\"fn\" action=\"index.php?option=com_comp\" method=\"post\">
// more not related stuff
<input type=\"image\" src=\"".JURI::root().
"components/com_comp/images/download_icon.png\" .
"\" name=\"downloadaddresses\">DOWNLOAD_RESULTS
// more not related stuff";
if($_POST['downloadaddresses_x']!=0) {
$myfilename = "tmp/results.txt";
$fh = fopen($myfilename, 'w');
$recipients = $_POST['recipients'];
$semicolon_separated = implode(";", $recipients);
fwrite($fh, $semicolon_separated);
fclose($fh);
/*header('Content-disposition: attachment; filename='.$myfilename);
header("Content-type: application/octet-stream");*/
echo "<a href=\"".$myfilename."\" id=\"downloadlink\">
This download should start automatically!</a>";
echo "<script type=\"text/javascript\">
newwindow=function{
window.open('".$myfilename."','name','height=400,width=200');
if (window.focus) {newwindow.focus()}}
</script>";
}
========================更多不起作用的代码================= =
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
答案 0 :(得分:1)
而不是这个click
模拟代码:
<script type="text/javascipt">
var el = document.getElementById('downloadlink');
if (document.createEvent) {
var event = document.createEvent(\"MouseEvents\");
event.initEvent(\"click\", true, true);
el.dispatchEvent(event);
}
else if (el.click) {
el.click();
}
</script>
你能用这个:
<script type="text/javascript">
location.href = document.getElementById('downloadlink').getAttribute('href');
</script>