Front end: Ajax calls export data to excel method, the method is executed but not downloaded

The back-end performs data query and returns the processing result to excel. The front-end uses ajax.

The initial wording is: fill in the interface path in the ajax url, the result code can run normally, but the page never pops up the download box

Reason: Ajax cannot directly export excel, because the return value of ajax can only be a character stream, and exporting excel is a binary byte stream written to the browser in the background

 

Method 1: form (recommended)

<a href="javascript:void(0)" onclick="exportExcel()">导出</a>
 
function exportExcel(){
     var form = $("<form>");
     form.attr('style', 'display:none');
     form.attr('target', '');
     form.attr('method', 'post');
     form.attr('action', '接口url');
 
     var input1 = $('<input>');
     input1.attr('type', 'hidden');
     input1.attr('name', '参数');
     input1.attr('value', '参数值');      /* JSON.stringify($.serializeObject($('#searchForm'))) */
 
     $('body').append(form);
     form.append(input1);
      
     form.submit();
     form.remove();   
}

Method two, window.location.href()

function() {
    window.location.href = "接口url?参数1=xxx&参数2=aaa";
}

Method 3: The ajax request caches the parameters in the back end and returns it to the front end, and the front end ajax initiates a window.open(url?params=params) again. 

$.ajax({
url: '接口url',
type: 'post',
dataType: "json",
contentType : 'application/json',
data : JSON.stringify(this.tableOpts),
success: function(data){
    window.open('接口url?params=xxxx');
}
});

 

Note that there is a front-end transfer limit when using window.open() or window.location.href(). If the number exceeds the limit, an error will be reported.

Microsoft Internet Explorer (Browser):IE浏览器对URL的最大限制为2083个字符,如果超过这个数字,提交按钮没有任何反应。

Firefox (Browser):对于Firefox浏览器URL的长度限制为65,536个字符

Safari (Browser):URL最大长度限制为 80,000个字符。

Opera (Browser):URL最大长度限制为190,000个字符。

Google (chrome):url最大长度限制为8182个字符

Regarding the difference between window.location and window.open(), the latter will open a new window when downloading. When the file is downloaded successfully, the window will be closed. Generally, if the download is fast enough, the window will not be visible! But the former download will not open a new window, it is recommended to use the former! 

 

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/107646212