js导出excel

不能使用jquery的$.ajax(),$.axax不能请求下载,

使用原生ajax或模拟表单提交

原生ajax:

 

 

 

  var xhr = new XMLHttpRequest();
                xhr.open('POST', URL, true);
                xhr.responseType = 'arraybuffer';
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.onload = function (e) {
                    //var data = new Uint8Array(this.response);
                    var blob = new Blob([this.response], { type: 'application/vnd.ms-excel,charset=utf-8' });
                    let url = window.URL.createObjectURL(blob);
                        var a = document.createElement("a");
                            a.setAttribute("href", url)
                            a.download = '库存帐查询.xlsx';
                            document.body.appendChild(a);
                            a.click()
                            document.body.removeChild(a);
                };
                //xhr.onreadystatechange = function () {
                //    // 这步为判断服务器是否正确响应
                //    if (xhr.readyState == 4 && xhr.status == 200) {
                //        var blob = new Blob([xhr.response], { type: 'application/vnd.ms-excel,charset=utf-8' });
                        
                //        let url = window.URL.createObjectURL(blob);
                //        var a = document.createElement("a");
                //            a.setAttribute("href", url)
                //            a.download = '库存帐查询.xlsx';
                //            document.body.appendChild(a);
                //            a.click()
                //            document.body.removeChild(a);
                //    }
                //};
                xhr.send(参数);

  

 

模拟表单提交

function download (options) {
            var defaults = {
                method: "GET",
                url: "",
                param: []
            };
            var options = $.extend(defaults, options);
            if (options.url && options.param) {
                var $form = $('<form action="' + options.url + '" method="' + (options.method || 'post') + '"></form>');
                for (var key in options.param) {
                    var $input = $('<input type="hidden" data-back="backjb" />').attr('name', key).val(options.param[key]);
                    $form.append($input);
                }
                $form.appendTo('body').submit().remove();
            };
        }

 

posted @ 2022-03-11 18:33  曲琦  阅读(100)  评论(0编辑  收藏  举报