Ajax PHP jQuery 实时保存计数器

ajax php jquery realtime saving of counter

本文关键字:保存 计数器 实时 jQuery PHP Ajax      更新时间:2023-09-26

目前脚本.php运行良好,但我想发生的是,而不是显示小时、分钟和秒,我希望将 3 个值组合并 POST 记录.php作为$_POST['timeSpent']以及每 1 秒$id $_POST['id']发送的值。

脚本.php

<p><span id="hours"></span>:<span id="minutes"></span>:<span id="seconds"></span></p>
<script>
  var sec = -1;
  function pad(val) { return val > 9 ? val : "0" + val; }
  setInterval(function () {
    $("#seconds").html(pad(++sec % 60));
    $("#minutes").html(pad(parseInt(sec / 60, 10) % 60));
    $("#hours").html(pad(parseInt(sec / 3600, 10)));
  }, 1000);
</script>

日志.php

<?php
    include 'includes/config.php';
    $loggeduser = $_SESSION['username'];
    $stmt = "UPDATE rotator_tracking SET time_spent=:time_spent WHERE id=:id";
    $stmt = $db->prepare($stmt);
    $stmt ->execute(array(
        ":time_spent" => $_POST['timeSpent'],
        ":id" => $_POST['id']
    ));
?>

我知道变量需要交给 ajax,ajax 将它们交给日志.php但在这种情况下,我不知道如何做到这一点,也不知道如何每 1 秒保存一次。

帮助?也许是示例代码。

在你的

setInterval循环中只需添加

$.post(
  'log.php',
  {
    timeSpent:theTimeCombinedVariable,
    id:IdVariable
  }
).done(function() {
  alert('done');
});

我没有测试代码。但差不多就是这样。