异步文件下载(不刷新不弹窗) /*** 异步文件下载(不刷新不弹窗)* @function fileDownload* @param {String} url 文件下载地址* @param {Object|String} [data] 请求参数,可以是类似jQuery的serializeArray(
/**
* 异步文件下载(不刷新不弹窗)
* @function fileDownload
* @param {String} url 文件下载地址
* @param {Object|String} [data] 请求参数,可以是类似jQuery的serializeArray()方法获取的数组形式;也可以直接是每个值都是字符串的对象。| 如果直接不带请求数据,该参数等于method
* @param {String} [method="GET"] 请求方式,可选:POST、GET
* @param {Number} [timeout=60000] 请求超时时间
*/
fileDownload = function (url, data, method, timeout) {
var iframeName = Math.random(),
$iframe = $('').appendTo("body"); // 为了避免页面跳转,采用创建临时iframe的方式
// 默认10s超时
timeout = timeout || 60000;
//如果直接不带请求数据,该第个参数等于method
if (typeof data === "string")
method = data;
if (method === "POST" || method === "post") { // POST 方式
var iframeDoc = $iframe[0].contentDocument || $iframe[0].contentWindow.document, // 获取iframe的document对象
$form = null;
// 为iframe写入一个form元素,利用该form元素发起文件下载请求
iframeDoc.write("");
$form = $(iframeDoc).find("form"); // 获取该form元素
// 带请求参数的情况
if (data instanceof Object) {
if (Array.isArray(data)) { // data是数组形式
data.forEach(function (o) {
if (o.value) $("").prop(o).appendTo($form);
});
} else { // data是对象形式
for (var n in data) {
$("").prop({ name: n, value: data[n] }).appendTo($form);
}
}
}
// 提交表单
$form.submit();
} else { // 默认 GET 方式
// 带请求参数的情况
if (data instanceof Object)
url = url + "?" + jQuery.param(data);
window.open(url, iframeName);
}
// 移除临时iframe
setTimeout(function () {
$iframe.remove();
}, timeout);
return this;
}
