我的 www / ajax / data.json 中的 .json 文件存储在我的服务器上,其中包含以下内容:
data.json
{
"Endorsements": [{
"Name": "Bob",
"Date": "01/02/2017",
"Message": "How's it going?"
}, {
"Name": "Sally",
"Date": "01/01/2017",
"Message": "Konichiwa"
}, {
"Name": "Sue",
"Date": "01/10/2017",
"Message": "Peace be unto you"
}, {
"Name": "Roger",
"Date": "02/12/2017",
"Message": "Namaste"
}, {
"Name": "Zed",
"Date": "09/12/2017",
"Message": "sup"
}, {
"Name": "Quail",
"Date": "10/12/2017",
"Message": "Chirp"
}]
}
messages.json 内容通过 messages.js messages.php 页面上每5秒成功显示和刷新一次>
在 messages.php 上,我有一个<form>
,用户可以在此留言。 名称,日期和消息字段中的输入条目通过 messages.js 中的函数存储在localStorage中
如何检索localStorage数据并使用它在我的 data.json 文件中附加新的消息条目?
答案 0 :(得分:0)
我希望这段代码可以帮助你,它只是一个用于将对象添加到现有json变量的函数。
var json = JSON.stringify({
"Endorsements": [{
"Name": "Bob",
"Date": "01/02/2017",
"Message": "How's it going?"
}, {
"Name": "Sally",
"Date": "01/01/2017",
"Message": "Konichiwa"
}, {
"Name": "Sue",
"Date": "01/10/2017",
"Message": "Peace be unto you"
}, {
"Name": "Roger",
"Date": "02/12/2017",
"Message": "Namaste"
}, {
"Name": "Zed",
"Date": "09/12/2017",
"Message": "sup"
}, {
"Name": "Quail",
"Date": "10/12/2017",
"Message": "Chirp"
}]
});
localStorage.setItem("newObject", JSON.stringify({
"Name": "test",
"Date": "01/02/2017",
"Message": "This is a test"
}));
function addToJsonFile(){
if(localStorage.getItem("newObject") !== undefined && localStorage.getItem("newObject") !== ""){
var jsonObjects = JSON.parse(json);
jsonObjects.Endorsements[jsonObjects.Endorsements.length] = JSON.parse(localStorage.getItem("newObject"));
json = JSON.stringify(jsonObjects)
}
}