我需要一个脚本,将html表单数据本地存储在设备上,直到用户在线,然后通过html操作提交表单。这可能吗?我是一个javascript新手,所以我喜欢任何可用的帮助。
答案 0 :(得分: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();
}
我希望这是有道理的。上述设置工作涉及很多工作,但它应该有效!