Javascript表单提交会创建大量的POST请求(多次提交)


Javascript form submit creates huge number of POST requests (multiple submit)

这是一个

奇怪的问题,如果我没有提供所有信息,请随时编辑问题或询问更多信息。

我有一个表单(定时测验(,如果用户未在固定时间内提交,则会自动提交,并在页面上显示倒计时时钟。

但是,当时间到期并提交表单时,浏览器会进入一种奇怪的状态,直到它崩溃,并且 Apache 日志会显示无穷无尽的 POST 请求列表。可能是什么原因造成的?

即使在我关闭浏览器窗口后,服务器仍然受到 POST 请求的打击。

如果我让窗口打开,Chrome 最终会显示一条失败消息,但 POST 请求仍然会进来,在显示此消息很久之后(我会说最多一分钟后(。有问题的错误可以在这里看到,以及记录POST请求的Apache日志文件:https://i.stack.imgur.com/Eci1z.jpg 或者如果我设法将其插入此处:!https://i.stack.imgur.com/Eci1z.jpg

这是一个Wordpress网站,但由我大量定制。我的.htaccess文件非常基本,我认为这不是问题所在。

相同的代码适用于网站的另一部分,使事情更难理解。

我还在WAMP(Apache 2.2.22/PHP 5.4.3(和运行PHP 5.5的生产服务器(不确定Apache版本(上进行了测试并获得了相同的行为。

.PHP:

define('REDIRECT_LINK', '/finish-free-iq-test.php');

Javascript:

function update_time_remaining() {
    var start_time_millis = Math.floor(jQuery("#start_time").val());
    var redir_to = "<?php echo REDIRECT_LINK; ?>";
    var test_duration = <?php echo Question::get_duration($questionSetID) * 1000;?>;
    var now = new Date();
    var remainingTime = test_duration - (now.getTime() - start_time_millis);
    if (remainingTime <= 0) {
//        console.log("time is out, redir to: " + redir_to);
//        alert("stop=");
        // force-submit the form
        jQuery("#answerForm").attr("action", redir_to);
        jQuery("#answerForm").submit();
    }
    else {
        var minutesRemaining = Math.floor(remainingTime / 60000);
        var secondsRemaining = Math.floor((remainingTime - minutesRemaining * 60000) / 1000);
        jQuery("#timer").html("Time remaining : " + (minutesRemaining<10?"0":"") + minutesRemaining + ":" + (secondsRemaining<10?"0":"") + secondsRemaining);
        //console.log(secondsRemaining);
    }   
}
// Things to do once the page has loaded (start the clock for example)
jQuery(document).ready(function() {
    jQuery("#submitRow").hide();
    jQuery("#start_time").val(new Date().getTime() - <?php echo (time() - $timeStarted)*1000; ?>);
    update_time_remaining();
    // check every half a second so the ticking is consistent looking.
    window.setInterval("update_time_remaining()", 500);

.HTML:

<div id="timer"></div> <br/>
<form id="answerswerForm" 
      method="POST" 
      action="<?php echo REDIRECT_LINK; ?>">
        <input id="submitRow" type="submit" name="go_next" value="Next question"> 
<?php echo "<input type='"hidden'" name='"current'" value='"$id'">"; ?>
<input type="hidden" name="answerswer" id="answerswer" value="-1">
<input type="hidden" name="start_time" id="start_time" value="<?php echo $jsTimeStarted; ?>">
</form>

乍一看,您似乎没有任何内容可以阻止以 500ms 的间隔调用"update_time_remaining(("。

这意味着"if (剩余时间 <= 0( {" 检查会被连续调用,即使在计时器低于零之后,也会导致重复的 post 调用,直到页面被卸载。

也许包含一个布尔标志,该标志只允许调用一次以下内容:

jQuery("#answerForm").submit();

一个好的解决方案是在调用提交后删除调用"update_time_remaining(("的间隔。

作为附加说明,请记住,由于这是一个仅限javascript的计时检查,因此具有足够专业知识(和时间(的人可以简单地禁用正在进行的检查,并随时提交答案。一个好的解决方案是检查该人在服务器端回答问题所花费的时间。