代码之家  ›  专栏  ›  技术社区  ›  user3576036

从客户端自动提交表单

  •  0
  • user3576036  · 技术社区  · 8 年前

    我有一个基于rails的测验应用程序。在服务器端,我将向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 回复  |  直到 8 年前
        1
  •  2
  •   GSSwain    8 年前

    您可以使用以下JS代码在30分钟后提交表单

    setTimeout(function(){ 
        document.getElementById("new_reply").submit();
    }, 1000 * 60 * 30);
    

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