我有一个网站,其中的变化是非常恒定的用户端。因此,为了防止每隔3-6秒为每个用户提交ajax请求,我希望等待用户完成操作,然后将所有操作提交给服务器。
因此,我不想提交很多非常小的ajax请求,而是在用户不活动(不更改任何内容)1分钟左右时,立即保存并提交所有请求。(有点像自动保存函数)
问题是,由于用户可以更新应用程序的不同部分,所以我需要在一个调用中更新不同的行,那么我将如何做呢?
因为POST变量需要一个标识符,所以我的第一个想法是提交一个id数组和另一个数据数组。然后在后端重建数组,迭代并相应地保存数据。但是有些东西告诉我这不是最佳的方法,你们能给我一些关于如何解决这个问题的建议吗?
发布于 2015-12-14 18:46:57
POSTing是一个表示页面DTO的JSON对象,怎么样?因此,您可以将后端所需的所有数据打包到一个对象中保存该页面的状态,如下所示:
{
'Attribute1' : 'Value1',
'Attribute2' : 'Value2',
'Attribute3' : 'Value3'
}我不知道您在服务器上使用什么来解析它,但是几乎任何值得使用的框架都可以相对轻松地处理JSON。
发布于 2015-12-14 19:26:19
您可以结合使用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) {
//...
}
// ... etchttps://stackoverflow.com/questions/34274138
复制相似问题