我正在尝试将一些数据保存到我的离线应用程序上的localStorage。当用户处于离线模式时,浏览器将从表单,FormData对象收集数据,将其存储到localStorage,当浏览器在线时,它将通过jQuery ajax将存储在localStorage中的FormData对象推送到服务器。复杂性是表单具有动态字段并且可以具有fileupload字段,问题是html5上的localStorage支持数据为字符串而不是对象。
Collection.prototype.storeOfflineData = function(collectionId){
var formData = new FormData($('form')[0]);
pendingSites = {"collectionId" : collectionId, "formData" : formData};
window.localStorage.setItem("offlineSites", JSON.stringify(pendingSites));
Collection.prototype.goHome();
Collection.prototype.showErrorMessage("Successfully store data in offline.");
}
当浏览器在线,连接到互联网时,我创建了从本地存储读取FormData的方法,并向服务器发出ajax请求,但是ajax请求收到错误,因为JSON.parse返回“[object object]”
Collection.prototype.pushingPendingSites = function(){
pendingSites = JSON.parse(window.localStorage.getItem("offlineSites"));
if(pendingSites != null){
console.log(pendingSites[i]["formData"]);
Collection.prototype.ajaxCreateSite(pendingSites[i]["collectionId"], pendingSites[i]["formData"]);
}
}
Collection.prototype.ajaxCreateSite = function(collectionId, formData){
$.ajax({
url: '/mobile/collections/' + collectionId + '/sites', //Server script to process data
type: 'POST',
success: function(){
Collection.prototype.goHome();
Collection.prototype.showErrorMessage("Successfully saved.");
},
error: function(data){
Collection.prototype.showErrorMessage("Save new site failed!");
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}