javascript 在本地保存 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28120177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save JSON File Locally
提问by Jesse Walton
I am designing an HTML5 website that allows you to create and position shapes with several attributes. The shapes are created as divs of class="shape" and the attributes are stored to each shape div using the data method. I'd like to be able to save the position and attributes of the shapes, in a JSON file, with a user defined name.
我正在设计一个 HTML5 网站,它允许您创建和定位具有多个属性的形状。形状创建为 class="shape" 的 div,并且使用 data 方法将属性存储到每个形状 div。我希望能够使用用户定义的名称将形状的位置和属性保存在 JSON 文件中。
Currently, I am using ajax and php to generate the JSON file and save it on the server.
目前,我正在使用 ajax 和 php 生成 JSON 文件并将其保存在服务器上。
Any ideas or thoughts on how it should be done? Bonus points for libraries, APIs and examples!
关于应该如何完成的任何想法或想法?库、API 和示例的奖励积分!
Clarification Edit: Saving to a discrete file in a user-defined location would be preferable. However, depending on the difficulty factor between the two options, browser storage could certainly suffice.
澄清编辑:保存到用户定义位置的离散文件会更可取。但是,根据两个选项之间的难度系数,浏览器存储肯定就足够了。
回答by user934801
I guess there are a lot of possibilities, but one is to use local storage and build some kind of syncronization with your current application. You can sync it with ajax or websockets or so on.
我想有很多可能性,但一种是使用本地存储并与您当前的应用程序构建某种同步。您可以将其与 ajax 或 websockets 等同步。
var updateLocalData = function(data){
if( supports_html5_storage() ){
localStorage.setItem('shape', JSON.stringify(data))
}
}
to sync your data get the written localStorage stuff and send it with your prefered method. And also keep in mind to use any kind of timestamp to always be able to find the latest version.
同步您的数据获取写入的 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;
}
回答by guest271314
Try
尝试
html
html
<input id="filename" type="text" placeholder="Please enter filename" />
<button for="filename">click</button><a id="download" download="" href=""></a>
<br />
<div class="shape"></div>
css
css
#download {
display:none;
}
js
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/
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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="filename" type="text" placeholder="Please enter filename" />
<button for="filename">click</button><a id="download" download="" href=""></a>
<br />
<div class="shape"></div>