在Ajax回调方法中通过window.open方法下载文件被浏览器拦截的解决方法

在Ajax回调方法中通过window.open方法下载文件被浏览器拦截的解决方法

问题描述

最近做一个导入导出的功能,需求是在Ajax中调用查询接口查出日志信息,生成Excel文件,放在tomcat目录下,然后在ajax回调方法中再使用window.open()方法调用导出日志的接口,下载日志文件,代码如下:
    dojo.xhrPost({
            url: this.webServicePath + "OutputAllLogs.jsp",
            content: content,
            timeout: this.timeout,
            preventCache: true,
            sync: false,
            load: dojo.hitch(this, function(response, ioArgs) {
                var json = dojo.fromJson(response);
                if (json[0] == null || json[0].ret != 0) {
                    alert(this.nls.LOG_SEARCH_FAIL);
                    this.btnOutput.cancel();
                    return;
                }
                if (json[0].content == null) {
                    consle.error("json.content == null");
                    this.btnOutput.cancel();
                    return;
                }
                this.btnOutput.cancel();

                if(json[0].content != ""){
                    fileName = "?fileName=" + json[0].content+"&absolutePath=1";
                    window.open(this.webServicePath + "DownloadLogsFile.jsp" + fileName);
                }
            }),
            error: dojo.hitch(this, function(response, ioArgs) {

                alert(this.nls.LOG_SEARCH_FAIL);
                this.btnOutput.cancel();
            })
        });
运行之后在IE11正常,但是在IE8下点击导出之后却马上闪退,无法导出。后来通过网上查资料,找到了问题的原因。

原因

在ajax的回调方法中使用window.open()方法下载文件,浏览器会认为这不是用户主动触发的动作,所以是不安全的,故被浏览器拦截。

解决方案

解决方案是把window.open()方法单独提到一个function中,在ajax回调方法中调用该function.
    dojo.xhrPost({
            url: this.webServicePath + "OutputAllLogs.jsp",
            content: content,
            timeout: this.timeout,
            preventCache: true,
            sync: false,
            load: dojo.hitch(this, function(response, ioArgs) {
                ...... //代码省略

                if(json[0].content != ""){
                    fileName = "?fileName=" + json[0].content+"&absolutePath=1";
                    this.downloadFile(fileName);
                }
            }),
            error: dojo.hitch(this, function(response, ioArgs) {

                alert(this.nls.LOG_SEARCH_FAIL);
                this.btnOutput.cancel();
            })
        });

    downloadFile:function(fileName) {
            window.open(this.webServicePath + "DownloadLogsFile.jsp" + fileName);
        }
再次运行,可以成功下载!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值