2016-03-24 60 views
0

我有下面的代碼,當用戶空閒時,它應該自動提交(保存)名爲「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> 

回答

1

這是刷新頁面window.location = location.href;嘗試取出它的代碼。

而且您還需要確保您的表單的屬性name正在替換document.project.submit();中的「項目」。

例如

<form name="test_form"></form> 

document.test_form.submit(); 


編輯:
好了,該功能應該只是

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

我將添加我的表單代碼 – Steven

+0

我知道它刷新,它應該是,它只是沒有提交它應該的形式 – Steven

+0

這是因爲你在提交之前重新加載頁面,你需要在重新加載頁面之前發送數據 –

0

,而不是做一個實際的表單提交,可考慮做一個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 
    }); 
} 
+0

我完全不熟悉Ajax。上面的代碼確實具有一定的常識,但「組裝數據在這裏」部分如何處理樣本數據除外? – Steven