简体   繁体   中英

Method undefined when calling it from $ajax.success

When I call a method from the $ajax.success callback I get an undefined.

var someObj = {};
someObj.someMethod = function() {
    //code code
}

someObj.ajaxCall = function() {
    $.ajax({
        //ajax options
    })
        .done(function( data ) {
            this.someMethod();
    });
}

As our good friend, Mr. SLaks has pointed out, you have a scope issue with regards to this

One solution other than the one posted could be saving a reference to the scope before the callback :

someObj.ajaxCall = function() {
    var _this = this;
    $.ajax({
        //ajax options
    })
        .done(function( data ) {
            _this.someMethod();
    });
}

Or, you can use the context option with $.ajax() to control the setting of the this value:

someObj.ajaxCall = function() {
    $.ajax({
        context: this,
        // other ajax options
    })
        .done(function( data ) {
            this.someMethod();
    });
}

You should use the call method of the function object:

someObj.ajaxCall = function() {
    $.ajax({
        //ajax options
    })
        .done(function( data ) {
            someMethod.call(someObj);
    });
}

Inside the success callback the this object is pointing the $ajax object which haven't a someMethod function defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM