我需要一個腳本,它將在設備上本地存儲html表單數據,直到用戶在線,然後通過html操作提交表單。這可能嗎?我是一個JavaScript新手,所以我很樂意提供任何幫助。提交HTML表單時用於離線的Javascript
-1
A
回答
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();
}
我希望這是有道理的。上面的設置工作涉及很多工作,但它應該工作!
相關問題
- 1. JavaScript錯誤提交HTML表單提交
- 2. 關於提交HTML表單
- 3. HTML表單提交到JavaScript表單
- 4. Javascript/html用返回鍵提交表單?
- 5. 使用Javascript(JQuery的)時提交表單
- 6. html表單提交使用javascript vs提交按鈕
- 7. 提交HTML表單
- 8. HTML表單提交
- 9. 提交HTML表單
- 10. Html表單提交
- 11. HTML表單提交
- 12. 用java提交html表單
- 13. HTML和Javascript:表單不會提交。
- 14. 將HTML表單數據提交給javascript
- 15. HTML + Javascript表單提交問題
- 16. 關於html表單提交服務器
- 17. 使用HTML,Javascript,MySQL和PHP合併提交表單時出錯
- 18. 使用JavaScript提交表單
- 19. 使用Javascript提交表單
- 20. 使用javascript提交表單?
- 21. 使用javascript提交表單
- 22. 表單提交使用javascript
- 23. 使用Javascript提交表單
- 24. 使用javascript提交表單
- 25. 用Javascript提交表單TypeError
- 26. Javascript表單提交
- 27. 的JavaScript:使用JavaScript填寫HTML表單並提交
- 28. 使用Firebase提交簡單表單;我可以在離線時檢測嗎?
- 29. html表單提交 - javascript不提交輸入按鈕
- 30. 當輸入用於提交時,AJAX表單提交
這是一個廣泛的主題,聽起來像它可能是[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
是的,但它是一個非常大的話題。使用搜索詞*首先離線*可能會有用。 – Quentin 2014-12-01 19:57:50