我正在使用 Electron 构建一个桌面应用程序。我想保留所有最近打开的文件的列表,为此我使用 jquery ajax。这是我的代码
// this function is expected to add a file entry to my json file
this.add_recent_file = function(file_id, file_name, date_opened) {
// Execute the ajax command.
$.ajax({
type: 'POST',
url: './data/recent-files.json',
dataType: 'json',
data: {
id: file_id,
name: file_name,
date: date_opened
},
success: function() {
console.log("Success");
}
});
}
这是我的示例 json 文件:
[
{
"id" : "1",
"name": "File.json",
"date": "24-feb-2018"
}
]
问题是控制台显示“成功”,但 json 文件没有更改。重新加载页面没有改变任何东西。
最佳答案
您可以使用node.js文件系统写入json文件。查看以下代码。
var fs = require('fs');
var $ = require('jquery');
this.add_recent_file = function (object) {
$.ajax({
type: 'GET',
url: './data/recent-files.json',
dataType: 'json',
success: function (files) {
// append the entry to the array.
files[files.length] = object;
// Get JSON string representation of the array.
var str = JSON.stringify(files);
// Now write it to the json file.
fs.writeFileSync(recent_file_url, str);
},
error: function () {
alert('Error updating json file.');
}
});
}
关于javascript - AJAX POST 成功但没有执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48973064/