PhoneGap javascript localStorage Android

时间:2013-09-17 15:23:03

标签: javascript android database cordova local-storage

所以我试图使用这种方法在PhoneGap应用程序中测试它: http://inflagrantedelicto.memoryspiral.com/2013/05/phonegap-saving-arrays-in-local-storage/

当代码到达时,我一直收到引用错误: window.localStorage.setItem window.localStorage.setArray

JS:

Storage.prototype.setArray = function (key,obj) {
    return this.setItem(key, JSON.stringify(obj));
}
Storage.prototype.getArray = function (key) {
    return JSON.parse(this.getItem(key));
}

var storedSettings = window.localStorage.getArray('mysettings');

alert('storedSettings = ' + storedSettings);
  if (storedSettings === null) {
      var settings = newArray();
  } else {
      var settings = storedSettings;
  }

$(document).ready(function() {



$('input[type=submit]').click(function() {
    alert('sup');
    var xsize = $('input[name=rads]:checked').attr('id');
    var xfirstname = $('#fname').val();
    var xsex = $('input[name=mf]:checked').attr('id');

    settings.push({'size':xsize, 'fname':xfirstname, 'sex':xsex});
    window.localStorage.setItem('mysettings', settings);
    window.localStorage.setArray('mysettings', settings);
    alert('settings:\n#1: ' + settings[0] + '\n#2: ' + settings[1] + '\n#3: ' + settings[2]); 
});



});

HTML:

<label for='small'>small</label>
<input type='radio' name='rads' id='small' checked='checked'/><br/>

<label for='medium'>medium</label>
<input type='radio' name='rads' id='medium'/><br/>

<label for='large'>large</label>
<input type='radio' name='rads' id='large'/>
<br/>
<br/>

<input type='text' id='fname' size='10'/>
<br/>

<label for='male'>M:</label>
<input type='checkbox' id='male' name='mf' checked='checked'/>
<br/>

<label for='female'>F:</label>
<input type='checkbox' id='female' name='mf'/>
<br/>
<br/>

<input type='submit' onclick='goset();' value='Save Settings'/>

1 个答案:

答案 0 :(得分:1)

经过一些研究,默认情况下会在PhoneGap中启用localStorage。

我认为你得到的参考错误是由于这一行:

var storedSettings = window.localStorage.getArray('mysettings');

在调用之前尝试检查数组是否存在:

if(window.localStorage.getArray('mysettings') !== undefined){
    var storedSettings = window.localStorage.getArray('mysettings');
else{
    var storedSettings = [] /*default settings and/or empty*/
}