如何在本地(在机器上)保存JSON数据?

我使用以下链接创建一个类似结构的树: LINK

这是我的代码:

    Tree Context Menu - jQuery EasyUI Demo        

Tree Context Menu and Drag Drop Tree Nodes

Right click on a node to display context menu.

Press mouse down and drag a node to another position.

Append
Remove
Expand
Collapse
function append(){ var t = $('#tt'); var node = t.tree('getSelected'); t.tree('append', { parent: (node?node.target:null), data: [{ text: 'new item1' },{ text: 'new item2' }] }); } function removeit(){ var node = $('#tt').tree('getSelected'); $('#tt').tree('remove', node.target); } function collapse(){ var node = $('#tt').tree('getSelected'); $('#tt').tree('collapse',node.target); } function expand(){ var node = $('#tt').tree('getSelected'); $('#tt').tree('expand',node.target); } function save(){ var a = document.createElement('a'); a.setAttribute('href','data:text/plain;charset=utf-u,'+encodeURIComponent(JSON.stringify({$('#tt').html()})); a.setAttribute('download', "data.json"); }

当我运行它时,没有任何东西被保存。

我在这个结构的代码中添加了一个保存按钮。

我希望每当用户单击此保存按钮时,他就可以将这个树结构存储为他/她的本地计算机上的JSON数据。 我希望这个,因为这棵树是可编辑的。 我怎样才能做到这一点?

我使用以下链接:

链接

我希望无论id =“tt”发生什么变化都可以以JSON的forms检索并存储在我的本地机器上。

当然可以这样做。

一旦你有了你的JSON字符串(我假设你知道如何获得它,因为如果不是那个完全不同的问题)你可以使用这个函数保存它:

 function saveText(text, filename){ var a = document.createElement('a'); a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text)); a.setAttribute('download', filename); a.click() } 

所以可能的用途可能是:

 var obj = {a: "Hello", b: "World"); saveText( JSON.stringify(obj), "filename.json" ); 

这将提示用于保存名为“filename.json”的文件,该文件包含obj的JSON对象

LocalStorage就是这么做的。

像这样用它:

 localStorage.setItem('myCat', 'Tom'); console.log(localStorage.getItem('myCat')); // Tom 

使用它也可以用来存储stringify -ed对象:

 var obj = { a : 1, b : 2}; localStorage.setItem('myObj', JSON.stringify(obj)); var obj2 = JSON.parse(localStorage.getItem('myObj'));