【问题标题】:Submit and save data on an ajax call for multiple rows at once一次提交并保存多行的ajax调用数据
【发布时间】:2015-12-14 18:32:47
【问题描述】:

我有一个网站,其中用户方面的变化非常稳定。因此,为了防止每 3-6 秒为每个用户提交一个 ajax 请求,我想等待用户完成操作,然后将所有操作提交给服务器。

因此,我不想提交许多非常小的 ajax 请求,而是希望在用户处于非活动状态(未更改任何内容)大约 1 分钟后一次提交所有请求。 (有点像自动保存功能)

问题是,由于用户可以更新应用程序的不同部分,我需要在一次调用中更新不同的行,那么我该怎么做呢?

由于 POST 变量需要一个标识符,我的第一个想法是提交一个 id 数组和另一个数据数组。然后在后端重建数组,迭代并相应地保存数据。但是有些事情告诉我这不是最佳方法,你们能给我一些关于如何解决这个问题的提示吗?

【问题讨论】:

标签: php jquery ajax


【解决方案1】:

您可以将setInterval$.ajax 结合使用,如下所示:

function saveData() {
    // Gather all the data you might want to post, in one object.
    // This should happen dynamically, you add to the object as things 
    // are entered and need to be sent to the server.
    // Some example data:
    data = { 
        name: $('#name').val(),
        age: $('#age').val(),
        occupation: $('#occupation').val(),
        list: [23, 1, 266, 34, 90],
        words: ["this", "is", "some", "data"],
        items: [{level: 11, width: 3}, {level: 22, width: 5}]
    };
    // If the data object is empty, it means there is nothing to save.
    // Of course, with the above example data this condition is false:
    if (!Object.keys(data).length) {
        return; // nothing to do
    } 
    // Post it
    $.ajax({
        url: 'script.php',
        type: 'POST',
        data: data,
    }).done(function(response) {
        alert(response);
        // Mark that this data was sent, as you might not want to send it
        // again the next round, unless the user changed some data.
        data = {};
    });
}

// Call the above function every 60 seconds.
setInterval(saveData, 60000);

在 PHP 中,您可以像这样访问您的数据:

// Access the items passed:
$name = $_POST['name'];
foreach ($_POST["list"] as $number) {
    //...
} 
// ... etc

【讨论】:

    【解决方案2】:

    如何为您的页面发布一个代表 DTO 的 JSON 对象?因此,您可以将后端保存该页面状态所需的所有数据打包到一个对象中,例如:

    {
        'Attribute1' : 'Value1',
        'Attribute2' : 'Value2', 
        'Attribute3' : 'Value3' 
    }
    

    我不确定您在服务器上使用什么来解析它,但几乎任何值得使用的框架都可以相对轻松地处理 JSON。

    【讨论】:

    • 我的问题是,我传递的每个值都已经是一个 json 对象,那么我该怎么做呢?构建一个json对象的json对象?
    • 当然,您可以将所有较小的对象包装/打包成一个较大的对象,并将其作为数据参数传递给 ajax 调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 2017-08-18
    • 2010-10-14
    • 1970-01-01
    • 2021-08-17
    • 2017-12-16
    相关资源
    最近更新 更多