在本地保存JSON文件

我正在设计一个HTML5网站,允许您创建和定位具有多个属性的形状。 形状创建为class =“shape”的div,并使用data方法将属性存储到每个形状div。 我希望能够在JSON文件中使用用户定义的名称保存形状的位置和属性。

目前,我使用ajax和php生成JSON文件并将其保存在服务器上。

关于如何做的任何想法或想法? 图书馆,API和示例的奖励积分!

澄清编辑:最好保存到用户定义位置的离散文件。 但是,根据两个选项之间的难度因素,浏览器存储肯定就足够了。

我想有很多可能性,但一个是使用本地存储并与您当前的应用程序构建某种同步。 您可以将它与ajax或websockets等同步。

 var updateLocalData = function(data){ if( supports_html5_storage() ){ localStorage.setItem('shape', JSON.stringify(data)) } } 

同步你的数据得到书面的localStorage东西,并用你喜欢的方法发送它。 并且还要记住使用任何类型的时间戳始终能够找到最新版本。

 var getLocalData = function(){ if( supports_html5_storage() ){ var userData = JSON.parse(localStorage.getItem('shape')); if(userData !== null){ return userData; } } var tStamp = getCurrentTimeStamp()+""; var obj = {}; obj[tStamp] = {"shapedata": ... }; return obj; } 

尝试

HTML

   

CSS

 #download { display:none; } 

JS

  $("[for=filename]").on("click", function (e) { var shape = $(".shape"), // provide `name` if no `input` `value` name = $("#filename").val() || "data-" + $.now(), url = /* `request` `url` */; // element data stuff shape.data("style", shape.css(["color", "width", "height"])); var request = function (url, filename) { var file = JSON.stringify(shape.data("style")); return $.ajax({ beforeSend: function (jqxhr, settings) { // `name` jqxhr.filename = filename; }, url: url, type: "POST", contentType: "application/json", dataType: "json", data: file }) .then(function (data, textStatus, jqxhr) { $("a#download").attr({ "download": jqxhr.filename + ".json", "href": "data:application/json;charset=utf8;base64," + window.btoa(JSON.stringify(data)) }).get(0).click(); }, function(jqxhr, textStatus, errorThrown) { console.log(textStatus, errorThrown) }); }; request(url, name) }); 

jsfiddle http://jsfiddle.net/guest271314/7rhs55k6/

请参阅属性下载

 $(function () { $("[for=filename]").on("click", function (e) { var shape = $(".shape"), name = $("#filename").val() || "data-" + $.now(), url = ""; shape.data("style", shape.css(["color", "width", "height"])); var request = function (url, filename) { var file = JSON.stringify(shape.data("style")); return $.ajax({ beforeSend: function (jqxhr, settings) { jqxhr.filename = filename; }, url: url, type: "POST", contentType: "application/json", dataType: "json", data: file }).always(function (jqxhr) { $("a#download").attr({ "download": jqxhr.filename + ".json", "href": "data:application/json;charset=utf8;base64," + window.btoa(this.data) }).get(0).click(); }); }; request(url, name) }); }) 
 #download { display:none; } .shape { color:green; width:50px; height:50px; }