下面是test.html的一段代码,为什么执行test1(),提示下载excel文件,而test2()打开excelexport.php之后,没有提示保存就自动关闭了?<input type="button" value="btn1" onclick="test1()"/>
<input type="button" value="btn2" onclick="test2()"/>
<script language="javascript" type="text/javascript">
function test1() {
window.open("excelexport.php");
}
function test2() {
window.setTimeout(test1,1);
}
</script>
excelexport.php的代码:<?php
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header('Content-Disposition:attachment;filename="charging.xls"');
header("Content-Transfer-Encoding:binary");
?>
<input type="button" value="btn2" onclick="test2()"/>
<script language="javascript" type="text/javascript">
function test1() {
window.open("excelexport.php");
}
function test2() {
window.setTimeout(test1,1);
}
</script>
excelexport.php的代码:<?php
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");
header('Content-Disposition:attachment;filename="charging.xls"');
header("Content-Transfer-Encoding:binary");
?>
window.setTimeout(function(){test1();},1);
我理解是iMilliSeconds毫秒之后,执行vCode指向的函数
<input type="button" value="btn1" onclick="test1()"/>
<input type="button" value="btn2" onclick="test2()"/>
<script language="javascript" type="text/javascript">
function test1() {
window.open("excelexport.php");
}
function test2() {
window.setTimeout(test1(),1);
}
</script>
把setTimeout 里的test1加个()
谢谢答复。这个方法可以正确执行test1(),但是是立即执行了,没有起到延迟效果
采用异步方式,不能正常下载
采用同步方式正常
<script language="javascript" type="text/javascript">
function test1() {
window.open("excelexport.php");
}
function test2() {
window.setTimeout(test1(),1000);
}
</script>
法1:window.setTimeout(function(){test1();},1000);
法2:window.setTimeout(“test1()”,1000);
法3:window.setTimeout(test1(),1000);
法1、法2在我的IE7环境下(XP、Vista都试了)没有导出excel提示,Firefox下正常
法3有导出excel提示,但是1000ms的定时不起作用,test1()在setTimeout的时候就执行了
这种浏览器问题很难说清楚,因为即使遵循了w3c标准,具体实现各个浏览器又有所不同,bug也就千奇百怪。
所以还是绕着走吧。
既然是链接到下载页面,为什么不直接location.href = 'excelexport.php',而要window.open('excelexport.php') ?
我项目中不是这样用的,其实就是放到了ajax的回调函数里,异步方式没法正确执行,同步方式可以
发现放在setTimeout里情况类似,就写了个简单的例子