javascript - AJAX POST 成功但没有执行任何操作

标签 javascript jquery json ajax electron

我正在使用 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/

相关文章:

javascript - 使用 document.head.appendChild() 附加具有 SRC 属性的脚本标签?

javascript - 如何在jquery中添加/删除下拉多选列表项

javascript - 数据表自定义行

python - 如何在 Python 中追加一个 json 文件?

json - 使用 Swift 更新字典数组中的值

javascript - 识别刷新和关闭浏览器操作

javascript - 当可以访问 DOM 时需要回调

javascript - 传单 map : marker's smooth transition opacity change

jquery - 使用 jQuery 显示/隐藏动态添加的 div

json - 是否可以在JSON中创建自定义对象键? [复制]