您可以将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