首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一次为多行提交和保存ajax调用上的数据

一次为多行提交和保存ajax调用上的数据
EN

Stack Overflow用户
提问于 2015-12-14 18:32:47
回答 2查看 1.1K关注 0票数 1

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

因此,我不想提交很多非常小的ajax请求,而是在用户不活动(不更改任何内容)1分钟左右时,立即保存并提交所有请求。(有点像自动保存函数)

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-14 18:46:57

POSTing是一个表示页面DTO的JSON对象,怎么样?因此,您可以将后端所需的所有数据打包到一个对象中保存该页面的状态,如下所示:

代码语言:javascript
复制
{
    'Attribute1' : 'Value1',
    'Attribute2' : 'Value2', 
    'Attribute3' : 'Value3' 
}

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

票数 0
EN

Stack Overflow用户

发布于 2015-12-14 19:26:19

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

代码语言:javascript
复制
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中,您可以像这样访问数据:

代码语言:javascript
复制
// Access the items passed:
$name = $_POST['name'];
foreach ($_POST["list"] as $number) {
    //...
} 
// ... etc
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34274138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档