Localstorage和Ajax调用

时间:2014-09-24 04:04:07

标签: javascript jquery ajax

您好我正在使用以下行从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错误在此代码段中的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){

            }

        });

}

1 个答案:

答案 0 :(得分:0)

它看起来不像本地存储问题。这更像是一个范围问题。当您尝试在函数内部访问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();
}

}