Javascript 本地存储和Ajax调用

Javascript 本地存储和Ajax调用,javascript,jquery,ajax,Javascript,Jquery,Ajax,您好,我正在使用此行从localstorage检索项目: var fetch_from_local = MyLocalStorage.getItem('saved_credits'); var username = MyLocalStorage.getItem('username'); send_to_server(fetch_from_local); 控制台日志显示了正确的对象,我需要将此对象发送回我的服务器,但我不能。我不明白为什么它会给我这个本地存储错误 当我尝试

您好,我正在使用此行从localstorage检索项目:

   var fetch_from_local =  MyLocalStorage.getItem('saved_credits');
   var username  =  MyLocalStorage.getItem('username');
   send_to_server(fetch_from_local);
控制台日志显示了正确的对象,我需要将此对象发送回我的服务器,但我不能。我不明白为什么它会给我这个本地存储错误

当我尝试包含我的$.ajax包装器时:我得到以下错误:
uncaughttypeerror:无法读取未定义的属性“push”
如果(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();
    }
}
发送到服务器功能
它看起来不像是本地存储问题。它更像是作用域问题。当您尝试在函数中访问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();
}

}

您在哪里使用
MyItem
?你应该在某处创建它的对象?同上@mithunsatheesh。您传递到
MyItem
的任何“对象”都没有属性
push
。因此它是未定义的。但我不会将任何内容推送到
MyItem
将项目推送到本地存储的行位于onclick事件中,不会被激发
saved\u credits
已在本地存储中。这说明未定义的不是
this.save()上的函数。
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();
}