从客户端自动提交表单

时间:2018-03-14 03:59:13

标签: javascript html

我在rails上构建了Quiz应用程序。在服务器端,我将向UI发送一个问题及其选项。目前,一旦用户点击提交按钮,就会创建数据。

我要做的是在该页面上设置30分钟计时器。而且我了解到从服务器端执行计时器操作并不是一种有效的方法。每隔一分钟或每分钟点击服务器听起来效率不高。

表单看起来像这样。

<form class="new_reply" id="new_reply" action="/quizzes/3/replies" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="1ImRYW1w" />

    <label>
  First war of Independence year
</label>
<div class="radio">
    <p>
      <label>
        1947
        <input type="radio" value="22" name="reply[answers_attributes][0][possible_answer_id]" id="reply_answers_attributes_0_possible_answer_id_22" />
        <input type="hidden" value="9" name="reply[answers_attributes][0][question_id]" id="reply_answers_attributes_0_question_id" />
      </label>
    </p>
    <p>
      <label>
        1857
        <input type="radio" value="23" name="reply[answers_attributes][0][possible_answer_id]" id="reply_answers_attributes_0_possible_answer_id_23" />
        <input type="hidden" value="9" name="reply[answers_attributes][0][question_id]" id="reply_answers_attributes_0_question_id" />
      </label>
    </p>
    <p>
      <label>
        1930
        <input type="radio" value="24" name="reply[answers_attributes][0][possible_answer_id]" id="reply_answers_attributes_0_possible_answer_id_24" />
        <input type="hidden" value="9" name="reply[answers_attributes][0][question_id]" id="reply_answers_attributes_0_question_id" />
      </label>
    </p>

</div>

  <input type="submit" name="commit" value="Finish quiz" class="btn btn-primary" />
</form>

我想让submit在30分钟后命中。有人可以帮忙吗?

js计时器

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

1 个答案:

答案 0 :(得分:2)

您可以使用以下JS代码

在30分钟后提交表单
setTimeout(function(){ 
    document.getElementById("new_reply").submit();
}, 1000 * 60 * 30);

计时器启动时在服务器端有一个时间戳,并与提交时的时间戳进行比较,并确保它们在正确的范围内。