在我的计划中,我使用JSON
获得JSON.stringify()
格式数据。现在我想将这个JSON
对象保存在文件中。
我的问题是:当点击JSON
上的按钮时,如何将jquery
数据保存在本地创建的文件中?
我的JSON
对象是这样的:
{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以使用Blob构造函数和URL.createObjectURL()创建一个临时锚标记,其download
属性设置为可下载文件应具有的名称,然后触发{{1该锚元素上的事件。遗憾的是,这不适用于任何浏览器,但对Blob constructor的支持实际上非常好。
这是一个例子。
click
var data = '{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}';
document
.querySelector('#download')
.addEventListener('click', function() {
var blob = new Blob( [ data ], {
type: 'application/octet-stream'
});
var url = URL.createObjectURL( blob );
var link = document.createElement( 'a' );
link.setAttribute( 'href', url );
link.setAttribute( 'download', 'data.json' );
link.click()
URL.revokeObjectURL(url)
})
答案 2 :(得分:0)
使用localStorage!这就像Cookies,但文件可能更大:
var json = '{"tasks":[{"blockId":"startpoint4","tasktype":"startpoint","properties":[],"positionX":430,"positionY":230},{"blockId":"userTask5","tasktype":"userTask","properties":[],"positionX":630,"positionY":230}],"connections":[],"properties":[],"numberOfElements":5}';
localStorage.setItem("json", json);
// if you want to use it, simply use localStorage.getItem("json")
console.log(JSON.parse(localStorage.getItem("json")));