weixin_33704591 2014-09-24 04:04 采纳率: 0%
浏览 15

本地存储和Ajax调用

Hello I am retrieving an item from localstorage using this line:

   var fetch_from_local =  MyLocalStorage.getItem('saved_credits');
   var username  =  MyLocalStorage.getItem('username');
   send_to_server(fetch_from_local);

the console log shows the correct object, I need to send this object back to my server, but I can't. I can't figure out why it's giving me this localstorage error.

When I try to include my $.ajax wrapper: I get the following error: Uncaught TypeError: Cannot read property 'push' of undefined the error is triggered on this line if (typeof this.item.push == 'function') { in this snippet:

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();
    }
}

Send to server function

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条回答 默认 最新

  • weixin_33671935 2014-09-24 04:13
    关注

    It doesn't look like local storage problem. It is more of scoping problem. When you try to access this.item inside function, scope of 'this' becomes function level scope. Copy this.item into a variable and use that variable inside function instead of 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();
    }
    

    }

    评论

报告相同问题?