使用计时器自动提交答案 (Javascript)

Auto Submit Answers With Timer (Javascript)

我正在尝试制作一个计时器,它会在时间到时自动提交所有答案。但是现在,它只是显示时间已过,并没有重定向到最终分数 page.My 答案存储在数据库中,我认为这没有关系。这是代码:

  $(document).ready(function() {
        var endTime = localStorage.getItem("endTime");
        console.log(endTime);
        
        if (endTime != 'underfined' && endTime != null) {
            startCountdownTimer();
            //localStorage.removeItem("endTime");
        }
        
    });

    function setEndTime() {
        var currentTime = new Date().getTime();
        var endTime = new Date(currentTime + 1*60000);
        localStorage.setItem("endTime", endTime);
        // alert('Set end time ' + endTime);

        startCountdownTimer();
    }

    function startCountdownTimer() {
        // Set the date we're counting down to
        var endTime = localStorage.getItem("endTime");
        var countDownDate = new Date(endTime).getTime();

        // Update the count down every 1 second
        var x = setInterval(function() {

            // Get today's date and time
            var now = new Date().getTime();

            // Find the distance between now and the count down date
            var distance = countDownDate - now;

            // Time calculations for days, hours, minutes and seconds
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);

            // Display the result in the element with id="demo"
            document.getElementById("demo").innerHTML = days + "d " + hours + "h "
            + minutes + "m " + seconds + "s ";

            // If the count down is finished,[ I want to make it is redirecting to score page ]
            if (distance <= 0) {
                clearInterval(x);
                setTimeout("document.quiz.submit()",1);
                window.location = "http://localhost/quizzer%202/final.php"
            }
                
        },1000);
    }

这是一个使用 JavaScript 的原生 setTimeout 功能自动提交表单的解决方案:

// The following ($function() {}) is equivalent to $(document).ready(function() {.
$(function() {
   setTimeout(function() {
      setTimeout(function() {$('#idOfYourForm').submit()},1);
      window.location = "http://localhost/quizzer%202/final.php"
   }, 1000 * 60 * 10); // This is the amount of milliseconds your test will last. I set this to ten minutes
});

此外,提交命令似乎不正确。由于您使用的是 jQuery,我将向您展示 jQuery 的方法。

  1. 为您的表单创建一个 ID
  2. $('#idOfYourForm').submit() 提交(一个问题是你在它周围加了引号)

最后一件事,当您提交表单时,默认操作是您将被重定向,因此您最后一次重定向不会执行任何操作。对于您所做的工作,请考虑使用 AJAX。 See this post.