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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29490643/article/details/78134737

在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);
        }
再次运行,可以成功下载!

猜你喜欢

转载自blog.csdn.net/qq_29490643/article/details/78134737