[英]Localstorage and Ajax call
您好,我正在使用此行從localstorage檢索項目:
var fetch_from_local = MyLocalStorage.getItem('saved_credits');
var username = MyLocalStorage.getItem('username');
send_to_server(fetch_from_local);
控制台日志顯示正確的對象,我需要將此對象發送回我的服務器,但不能。 我不知道為什么它會給我這個本地存儲錯誤。
當我嘗試包含$ .ajax包裝器時:我收到以下錯誤: Uncaught TypeError: Cannot read property 'push' of undefined
的Uncaught TypeError: Cannot read property 'push' of undefined
if (typeof this.item.push == 'function') {
在此片段中:
function MyItem(object, key) {
this.item = object;
this.key = key;
this.addSubItem = function(subItem) {
if (typeof this.item.push == 'function') {
this.item.push(subItem);
this.save();
return this;
}
return false;
};
this.setItem = function(object) {
this.item = object;
this.save();
return this;
};
this.save = function() {
MyLocalStorage.setItem(this.key, this.item);
};
this.toString = function() {
return this.item.toString();
}
}
function send_to_server(fetch_from_local)
{
$.ajax({
url: '',
type: 'POST',
data: {user: fetch_from_local},
beforeSend:function(){
},
success:function(data){
btn.button('reset');
obj = JSON.parse(data);
},
error:function(data){
}
});
}
它看起來不像本地存儲問題。 這更多是范圍界定問題。 當您嘗試訪問函數內部的this.item時,“ this”的范圍變為函數級范圍。 將this.item復制到變量中,然后在函數內部使用該變量而不是this.item。
function MyItem(object, key) {
this.item = object;
this.key = key;
var myItem = this;
this.addSubItem = function(subItem) {
if (typeof myItem.item.push == 'function') {
myItem.item.push(subItem);
myItem.save();
return this;
}
return false;
};
this.setItem = function(object) {
this.item = object;
this.save();
return this;
};
this.save = function() {
MyLocalStorage.setItem(this.key, this.item);
};
this.toString = function() {
return this.item.toString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.