这是场景:一个发问者包括3个问题,每个问题有4个多重答案。用户将选择每个问题的答案,这些数据将以隐藏形式存储在标签中,即

<label id=q1>A</label>
<label id=q2>C</label>
<label id=q3>D</label>


现在,如果设备已连接到互联网,则可以轻松提交这些数据,但是如果设备没有互联网,我需要找到一种方法来将标签数据存储在用户的设备上,然后下次连接时,应用程序有一个提交按钮,它将提交所有存储的数据(每次回答提问者时)。

谢谢

最佳答案

我要做的是将数据保存在localStorage中(尽管此链接指向Phonegap Docs,localStorage是Html5功能,非常有用),然后定期调用一个函数来检查是否有要发送的内容。

因此,要检查网络连接可用性:

function isOnline(){
    try{
        var status = navigator.network.connection.type;
        var val = (status != 'none' && status != 'unknown');
        return val;
    }catch(err){ console.error('isOnline(): '+err); return false; }
}


包括以下代码行以向localStorage添加一些功能,因为它只允许保存字符串,但是通过这两个功能,它也能够存储JSON数据:

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}


在您的表单提交处理程序中,只需检查是否存在连接即可。如果没有,请保存要发送的数据:

if(isOnline()){
    // do stuff
}else{
    var data = // The data to be sent
    var toBeSent = localStorage.getObject('toBeSent') || [];
    toBeSent.push(data);    // It's better to store the data in an array, in case there's more than a questioner to be sent
    localStorage.setObject('toBeSent', toBeSent);
}


之后,编写一个检查并发送数据的函数:

function sendPending(){
    var toBeSent = localStorage.getObject('toBeSent') || [];
    var data;
    for(var i in toBeSent){
        data = toBeSent[i];

        // send data
    }
    // Remove the list
    localStorage.removeItem('toBeSent');
}


最后,要定期执行该功能:

setInterval(sendPending, 60000);  // The system will check every minute if there's something to send

关于javascript - 如何通过HTML 5 javascript在本地ipad/iphone上存储数据并在设备在线时提交数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11897012/

10-09 23:58
查看更多