在服务器上存储和更新JSON数据
我的web应用程序应该能够在服务器上存储和更新(同时加载)JSON数据。 但是,数据可能包含一些大数组,每次保存时只追加一个新条目 我的解决方案: 使用json数据中的密钥路径向服务器发送更新 目前,我通过jquery使用xmlhttprequest发送数据,如下所示在服务器上存储和更新JSON数据,json,store,Json,Store,我的web应用程序应该能够在服务器上存储和更新(同时加载)JSON数据。 但是,数据可能包含一些大数组,每次保存时只追加一个新条目 我的解决方案: 使用json数据中的密钥路径向服务器发送更新 目前,我通过jquery使用xmlhttprequest发送数据,如下所示 /** * Asynchronously writes a file on the server (via PHP-script). * @param {String} file complete filename (path
/**
* Asynchronously writes a file on the server (via PHP-script).
* @param {String} file complete filename (path/to/file.ext)
* @param content content that should be written. may be a js object.
* @param {Array} updatePath (optional), json only. not the entire file is written,
* but the given path within the object is updated. by default the path is supposed to contain an array and the
* content is appended to it.
* @param {String} key (optional) in combination with updatePath. if a key is provided, then the content is written
* to a field named as this parameters content at the data located at the updatePath from the old content.
*
* @returns {Promise}
*/
io.write = function (file, content, updatePath, key) {
if (utils.isObject(content)) content = JSON.stringify(content, null, "\t");
file = io.parsePath(file);
var data = {f: file, t: content};
if (typeof updatePath !== "undefined") {
if (Array.isArray(updatePath)) updatePath = updatePath.join('.');
data.a = updatePath;
if (typeof key !== "undefined") data.k = key;
}
return new Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: io.url.write,
data: data,
success: function (data) {
data = data.split("\n");
if (data[0] == "ok") resolve(data[1]);
else reject(new Error((data[0] == "error" ? "PHP error:\n" : "") + data.slice(1).join("\n")));
},
cache: false,
error: function (j, t, e) {
reject(e);
//throw new Error("Error writing file '" + file + "'\n" + JSON.stringify(j) + " " + e);
}
});
});
};
在服务器上,php脚本管理其余部分,如下所示:
- 阅读并解码json
- 返回关于无效json的错误
- 只要写下数据
- 如果无法遍历JSON数据中的更新路径(或文件不存在),则返回错误
注意:我更喜欢只使用php或一些标准apache的解决方案
非常感谢。然而,我不大可能对服务器进行大量修改。但我会看看你的代码!关于3:事实上,我没有有意的并发写访问-如果不应该发生在同一个文件上。