【问题标题】:AJAX POST successful but does not do anythingAJAX POST 成功但不执行任何操作
【发布时间】:2018-08-04 23:57:14
【问题描述】:

我正在使用电子构建一个桌面应用程序。我想保留所有最近打开的文件的列表,为此我使用的是 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 文件没有变化。重新加载页面并没有改变任何东西。

【问题讨论】:

  • 是您的服务器端代码对文件进行了更改,也许您应该显示它?使用电子方法,您可以将文件直接保存在“客户端”。
  • 无论何时您将某些内容发布到 JSON 文件,它都不会自行更改。您需要某种后端来为您执行此操作。您正在运行 PHP 服务器吗?在这种情况下,将其发布到服务器并编写一些服务器代码来更新 JSON 文件。
  • @GerritLuimstra 看起来他们正在使用电子。
  • @Teemu 啊,是的,刚刚检查了回购。我不太熟悉。

标签: javascript jquery json ajax electron


【解决方案1】:

您可以使用 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.');
        }
    });
}

【讨论】:

    【解决方案2】:

    正如@Gerrit Luimstra 所说,你需要一个后端,如果你使用的是 PHP,你可能会使用这样的东西:

    data/update.php
    <?php
    $id = $_POST['id'];
    $name = $_POST['name'];
    $dateX = $_POST['date'];
    
    //update database code here
    

    【讨论】:

    • 看来他们使用的是 Electron 而不是 PHP 作为“后端”
    • Electron 使用 node.js
    【解决方案3】:

    现在您正在使用 AJAX 将数据 POST 到 JSON 文件,并希望这会更新文件。然而事实并非如此。

    您可以改为使用 Electron 的文件系统将更改写入 JSON 文件。

    在这种情况下,你的函数会变成这样:

    this.add_recent_file = function(file_id, file_name, date_opened) {
        // Create the JSON content
        var data = {
                id: file_id,
                name: file_name,
                date: date_opened
            };
    
       // If you want to prettify the JSON content
       data = JSON.stringify(data, null, 2);
    
    
        // Write it to the file
        fs.writeFileSync('../path/to/recent-files.json', data);
    
    }
    

    然而,这需要您使用节点文件系统包。

    【讨论】:

    • 没关系,但是会删除之前的文件内容,解析json时出现语法错误
    • @Mohit 我建议简单地查看如何在 Node.js 中读取/写入文件。这与 jQuery 无关,甚至与网络无关。
    猜你喜欢
    • 1970-01-01
    • 2016-07-31
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多