jQuery 生成下载文件

jquery.generateFile.js

(function($){

// Creating a jQuery plugin:

$.generateFile = function(options){

options = options || {};

if(!options.script || !options.filename || !options.content){
throw new Error("Please enter all the required config options!");
}

// Creating a 1 by 1 px invisible iframe:

var iframe = $('<iframe>',{
width:1,
height:1,
frameborder:0,
css:{
display:'none'
}
}).appendTo('body');

var formHTML = '<form action="" method="post">'+
'<input type="hidden" name="filename" />'+
'<input type="hidden" name="content" />'+
'</form>';

// Giving IE a chance to build the DOM in
// the iframe with a short timeout:

setTimeout(function(){

// The body element of the iframe document:

var body = (iframe.prop('contentDocument') !== undefined) ?
iframe.prop('contentDocument').body :
iframe.prop('document').body; // IE

body = $(body);

// Adding the form to the body:
body.html(formHTML);

var form = body.find('form');

form.attr('action',options.script);
form.find('input[name=filename]').val(options.filename);
form.find('input[name=content]').val(options.content);

// Submitting the form to download.php. This will
// cause the file download dialog box to appear.

form.submit();
},50);
};

})(jQuery);


调用方法:

$(document).ready(function(){

$('#download').click(function(e){

$.generateFile({
filename : 'export.txt',
content : $('textarea').val(),
script : 'download.php'
});

e.preventDefault();
});

$('#downloadPage').click(function(e){

$.generateFile({
filename : 'page.html',
content : $('html').html(),
script : 'download.php'
});

e.preventDefault();
});

});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值