是否可以仅将数据写入本地json文件中?
不会。即使您是从本地文件系统(例如
file://myfile.html)或本地Web服务器(例如
http://localhost/myfile.html或
http://host-on-my-intranet/myfile.html)运行页面,您仍然无法直接从浏览器托管的Javascript代码写入文件。
两种选择:
将其发送到可以将其写出的内容(例如服务器),或者
提供它作为
data:
URI(如果可以的话),用户可以右键单击并选择“另存为…”。
这是
data:为一些JSON文本创建URI的方法:
var uri = "data:application/json;charset=UTF-8," + enpreURIComponent(theJSON);
*#2的 *完整示例 :
var theData = { foo: "bar"};var theJSON = JSON.stringify(theData);var uri = "data:application/json;charset=UTF-8," + enpreURIComponent(theJSON);var a = document.createElement('a');a.href = uri;a.innerHTML = "Right-click and choose 'save as...'";document.body.appendChild(a);


