我想存储我网页上的输入数据。 联机时,数据存储在数据库中,但是当我离线使用页面时,我也希望存储输入数据。 输入数据包含一些输入按钮,一个注释框和当前时间戳。 当我连接到Internet时,我想将数据上传到数据库。 你有一个想法怎么做? 我想到过车契清单吗?或者,也许将页面中的数据存储在一个文本文件中,然后将其上传到数据库。
希望您能帮助我:)
答案 0 :(得分:0)
一种选择是使用Java脚本保存到浏览器的LocalStorage中。即使关闭浏览器窗口,您的数据也将保存在本地,没有到期日期。
用法很简单:
var user = {
username: "john.doe",
email: "john.doe@mail.com"
}
window.localStorage.setItem('user', JSON.stringify(user));
一种实现它的方法可能是(使用JQuery)。我目前无法测试此代码是否可以正常工作,但我相信您可以理解:
我正在使用Javascript的navigator.online检查连接性。
profile.html
<html>
<body>
<form action="save_profile.php">
Name:<br>
<input type="text" name="name">
<br>
Email:<br>
<input type="text" name="email">
<br><br>
<input type="submit" value="Save" onclick="validate()">
</form>
</body>
</html>
<script>
$(document).ready(function() {
//This synch can be executed on every page
var needsSynch = window.localStorage.getItem('needs_synch');
if (needsSynch) {
synchronizeOfflineData();
}
function synchronizeOfflineData()
{
var userData = JSON.parse(window.localStorage.getItem('user_data'));
$.ajax({
url : "save_profile.php",
type : 'post',
data : {
nome : userData.name,
email : userData.email
},
success: function(result){
window.localStorage.setItem('needs_synch', false);
window.localStorage.removeItem('user_data');
}
});
}
function validate()
{
//submit form if you are offline
if (window.navigator.online) {
return true;
}
saveToLocalStorage();
window.top.location= = "http://yourdomain.com/offline_success_page.html";
}
function saveToLocalStorage()
{
var userData = {
name: $('input[name=name]').value,
email: $('input[name=email]').value
};
//a flag to indicate that there is data waiting to synchronize when online
window.localStorage.setItem('needs_synch', true);
window.localStorage.setItem('user_data', JSON.stringify(userData));
}
});
</script>