码迷,mamicode.com
首页 > Web开发 > 详细

Js -----后台json数据,前端生成下载text文件

时间:2017-09-21 16:38:54      阅读:1048      评论:0      收藏:0      [点我收藏+]

标签:弹框   技术分享   ima   int   方法   blob   click   cti   code   

 

需要引入

<script src="/assets/libs/single_file/jquery.min.js"></script>
<script src="/assets/libs/layer/layer.js"></script>

借鉴 张鑫旭文章

http://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/

 1  // 返回错误信息弹框显示
 2     @if (session(‘point_errors‘))
 3         var point_errors = JSON.stringify({!! session()->pull(‘point_errors‘) !!});
 4          point_errors = JSON.parse( point_errors );
 5         // console.log(point_errors);
 6         var text_content = ‘‘,msg = ‘‘,layer_content = ‘<p><input type="button" id="download_text" value="点击下载文件"></p>‘;
 7         $.each(point_errors, function(index, item) {
 8             // 组织text内容
 9             text_content += item[0] + ‘ ‘ + item[1] + ‘ ----‘
10                 + item[2] + ‘\r\n‘;
11 
12             msg = ‘<p style="padding:0;margin:0">‘+item[1] + ‘[‘
13                 +  item[0] + ‘]----‘
14                 +  item[2] + ‘</p>‘;
15             layer_content += msg;
16         });
17 
18         console.log(layer_content);
19         console.log(text_content);
20 
21         // 下载文件方法
22         var funDownload = function (content, filename) {
23             var eleLink = document.createElement(‘a‘);
24             eleLink.download = filename;
25             eleLink.style.display = ‘none‘;
26             // 字符内容转变成blob地址
27             var blob = new Blob([content]);
28             eleLink.href = URL.createObjectURL(blob);
29             // 触发点击
30             document.body.appendChild(eleLink);
31             eleLink.click();
32             // 然后移除
33             document.body.removeChild(eleLink);
34         };
35 
36         if (‘download‘ in document.createElement(‘a‘)) {
37             // 作为test.html文件下载
38             $(document).on(‘click‘, ‘#download_text‘, function () {
39                 funDownload(text_content, ‘导入失败的用户信息.text‘);
40             });
41         } else {
42             $(document).on(‘click‘, ‘#download_text‘, function () {
43                 alert(‘浏览器不支持‘);
44             });
45         }
46 
47         setTimeout(function(){
48             layer.open({
49                 type: 1,
50                 area: [‘500px‘, ‘600px‘],
51                 content: layer_content,
52                 scrollbar: true
53             });
54         }, 2000);
55     @endif

技术分享

 

Js -----后台json数据,前端生成下载text文件

标签:弹框   技术分享   ima   int   方法   blob   click   cti   code   

原文地址:http://www.cnblogs.com/smallyi/p/7569055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!