jquery导出并下载报表的方式
生活随笔
收集整理的這篇文章主要介紹了
jquery导出并下载报表的方式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在項(xiàng)目中碰到需要導(dǎo)出報(bào)表(并且是帶參數(shù)的)
然后就想著通過(guò)文件流的形式下載
1.模擬表單提交的形式
var $form = $("<form id='exportForm' method='post' ></form>");$form.attr({'action':action,'method':'post'});$form.append($("<input type='hidden' name='columns' value='"+JSON.stringify(columns)+"' />"));$form.append($("<input type='hidden' name='fields' value='"+JSON.stringify(fields)+"'/>"));$form.appendTo("body");$form.css('display','none');$form.submit();但是這種表單提交的方式有點(diǎn)難受,導(dǎo)出的時(shí)候你不知道他多久返回結(jié)果,這種情況下就很難去控制遮罩時(shí)間,數(shù)據(jù)量一大,導(dǎo)出沒(méi)見(jiàn)出來(lái)然后就一頓點(diǎn)導(dǎo)出,結(jié)果可想而知。
所以就想著有沒(méi)有方法可以讓他有返回函數(shù),第二種方法就這樣來(lái)了。
2 .XMLHttpRequest
function ExportFile(url, data, loadSuccess, timeout) {$.messager.progress({msg:'正在導(dǎo)出處理,請(qǐng)耐心等待...'});//loading效果var xmlResquest = new XMLHttpRequest();xmlResquest.open("POST", url, true);xmlResquest.setRequestHeader("Content-type", "application/json");xmlResquest.timeout = timeout || (1000 * 60);// 超時(shí)時(shí)間,單位是毫秒xmlResquest.responseType = "blob";//該屬性必須設(shè)置xmlResquest.onload = function (oEvent) {$.messager.progress('close');//關(guān)閉loading效果var retData = { Success: true, errorMsg: ["導(dǎo)出成功!"] };var content = xmlResquest.response;var blob = new Blob([content]);if (xmlResquest.getResponseHeader("content-disposition")) {//判斷有沒(méi)有請(qǐng)求頭content-disposition,該請(qǐng)求頭在后臺(tái)文件流導(dǎo)出成功時(shí)添加var explorer = navigator.userAgent;var elink = document.createElement('a');var fileName = xmlResquest.getResponseHeader("content-disposition").split(";")[1].split("=")[1];//獲取文件名//響應(yīng)頭中的內(nèi)容如果包含中文會(huì)出現(xiàn)亂碼,需要解碼才能正常顯示if (explorer.indexOf("MSIE") >= 0 || explorer.indexOf("Chrome") >= 0) { //IE和google瀏覽器fileName = decodeURIComponent(fileName);} else {fileName = decodeURI(escape(fileName));}elink.download = fileName;elink.style.display = 'none';elink.href = window.URL.createObjectURL(blob);document.body.appendChild(elink);elink.click();document.body.removeChild(elink);window.URL.revokeObjectURL(url);if (loadSuccess && $.isFunction(loadSuccess)) loadSuccess(retData, oEvent);} else {//后臺(tái)出現(xiàn)異常時(shí)的處理var r = new FileReader();r.readAsText(blob, 'utf-8');r.onload = function (e) {if (loadSuccess && $.isFunction(loadSuccess)) loadSuccess(JSON.parse(r.result), oEvent);}}};xmlResquest.ontimeout = function (e) {$.messager.progress('close');$.messager.error("導(dǎo)出超時(shí),請(qǐng)重新導(dǎo)出!");};xmlResquest.onerror = function (e) {$.messager.progress('close');$.messager.error("導(dǎo)出時(shí)出現(xiàn)錯(cuò)誤,導(dǎo)出失敗!");};xmlResquest.send(JSON.stringify(data));//發(fā)送請(qǐng)求}總結(jié)
以上是生活随笔為你收集整理的jquery导出并下载报表的方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: nested exception is
- 下一篇: 寒假的牛客训练赛1补题