空闲时自动保存表单

Autosave form on idleness

本文关键字:保存 表单      更新时间:2023-09-26

我有下面的代码,它应该在用户空闲时自动提交(保存)一个名为"project"的表单。这是我在教程网站上找到的代码(忘记名字),我试过了,它只刷新了页面?

<!-- Set auto save timeout in milliseconds 
<script type="text/javascript">
attachEvent(window,'load',function(){
  var idleSeconds = 5;
  var idleTimer;
  function resetTimer(){
    clearTimeout(idleTimer);
    idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
  }
  attachEvent(document.body,'mousemove',resetTimer);
  attachEvent(document.body,'keydown',resetTimer);
  attachEvent(document.body,'click',resetTimer);
  resetTimer(); // Start the timer when the page loads
});
function whenUserIdle(){
        document.project.submit();
        window.location = location.href;
}
function attachEvent(obj,evt,fnc,useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evt,fnc,!!useCapture);
    return true;
  } else if (obj.attachEvent){
    return obj.attachEvent("on"+evt,fnc);
  }
} 
</script> -->

表单代码:

<form name="project" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="invoice-form" method="post"  class="invoice-form" role="form" novalidate> 

这是刷新页面window.location = location.href;的代码。尝试删除它。

您还需要确保表单的属性name正在替换document.project.submit();中的"项目"。

例如

<form name="test_form"></form>
document.test_form.submit();


编辑:
好的,函数应该只是

function whenUserIdle() {
    document.project.submit();
}

与其进行实际的表单提交,不如考虑进行AJAX请求:

function whenUserIdle(){
  var formData = {}; // assemble the form data here
  $.post( "/form-submission-route", formData, function( responseData) {
    // do something with result, if you like
    // perhaps clear the form or throw up a notification
  });
}