在项目开发过程中,前端和后端经常是并行的。这时前端难免需要在本地"制造"出符合指定格式要求的数据。大部分数据都是使用json格式,那么有什么好的方法能直接保存json对象到本地呢?今天发现了以下方法:
1 (function(console){
2
3 console.save = function(data, filename){
4
5 if(!data) {
6 console.error('Console.save: No data')
7 return;
8 }
9
10 if(!filename) filename = 'console.json'
11
12 if(typeof data === "object"){
13 data = JSON.stringify(data)
14 }
15
16 var blob = new Blob([data], {type: 'text/json'}),
17 e = document.createEvent('MouseEvents'),
18 a = document.createElement('a')
19
20 a.download = filename
21 a.href = window.URL.createObjectURL(blob)
22 a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
23 e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
24 a.dispatchEvent(e)
25 }
26 })(console)
2
3 console.save = function(data, filename){
4
5 if(!data) {
6 console.error('Console.save: No data')
7 return;
8 }
9
10 if(!filename) filename = 'console.json'
11
12 if(typeof data === "object"){
13 data = JSON.stringify(data)
14 }
15
16 var blob = new Blob([data], {type: 'text/json'}),
17 e = document.createEvent('MouseEvents'),
18 a = document.createElement('a')
19
20 a.download = filename
21 a.href = window.URL.createObjectURL(blob)
22 a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
23 e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
24 a.dispatchEvent(e)
25 }
26 })(console)
效果非常赞!