2014-12-01 21 views
-1

我需要一個腳本,它將在設備上本地存儲html表單數據,直到用戶在線,然後通過html操作提交表單。這可能嗎?我是一個JavaScript新手,所以我很樂意提供任何幫助。提交HTML表單時用於離線的Javascript

+0

這是一個廣泛的主題,聽起來像它可能是[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem),並且你還沒有顯示[你試過的](http://mattgemmell.com/what-have-you-tried/)。請詳細說明該用例的具體含義,並向您展示解決方案的嘗試。 – zzzzBov 2014-12-01 19:56:22

+0

是的,但它是一個非常大的話題。使用搜索詞*首先離線*可能會有用。 – Quentin 2014-12-01 19:57:50

回答

1

我認爲這是可行的。以下是我如何做,儘管它可能不理想。

設置您的表單,以便提交操作由javascript處理。它應該嘗試提交表單,如XMLHttpRequest或jQuery的ajax()函數。 爲提交請求設置回調。成功時,向用戶指示或導航到新的頁面,但是您想要顯示請求已成功。失敗時(任何失敗或使用結果的狀態碼來確認用戶無法連接),您有兩種選擇。 一種選擇是做一個合理長度的setTimeout並再次嘗試提交動作。但是,如果用戶關閉頁面或導航,這絕不會完成。 另一種選擇是將表單數據放入某種數組中,並將其放入localStorage對象中。然後,如果他們重新加載頁面,您可以看到數據是否存在。如果是這樣,它可以重新填充表單並提示用戶嘗試新的提交。如果提交成功,請清空本地存儲。 我會這樣做的方式將是兩者的結合。這是一些僞代碼。

//run this once document is ready 

//our submitForm action 
var submitForm = function() { 
    var url = "my_form_action.php"; 
    var params = "foo=bar"; //set params to your form values here 
    localStorage.myFormData = params; 
    http.open("POST", url, true); 

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    http.setRequestHeader("Content-length", params.length); 
    http.setRequestHeader("Connection", "close"); 

    //Call a function when the state changes. 
    http.onreadystatechange = function() { 
     if(http.readyState == 4) { 
      if(http.status == 200) { 
       //call was completed successfully 
       //clear out our local storage 
       localStorage.myFormData = null; 

       //do whatever here! (tell the user it was successful, change pages, whatever) 
       //doStuff(); 
      } else { 
       //call was unsuccessful (user is offline) 
       //attempt again in 10 seconds 
       window.setTimeout(submitForm, 10000); 
      } 
     } 
    } 
    http.send(params) 
} 

//on document ready, check if we have pending form data to send 
//if we do, fill in our form and attempt to submit it 
if(localStorage.myFormData) { 
    //my data exists 
    //fill the form back out using stuff like 
    //document.getElementById('FirstName').value = localStorage.myFormData.match(/(.+?)=(.+?)(?:&|$)/g)[1][1]; 
    //you'll need to figure out how best to repopulate your form when the page loads, but do it here 

    //once form is repopulated, either submit it using the form.submit function or call our submitForm() function directly 
    submitForm(); 
} 

我希望這是有道理的。上面的設置工作涉及很多工作,但它應該工作!