如何在ajax中传递上下文

How to pass context to done in ajax

本文关键字:上下文 ajax      更新时间:2023-12-01

以下是场景:

getSomething: function(){
    var gotValue = sendAjax();
    gotValue.done(function(response){
        console.log(response); //How to pass context of object to call getSomethingElse
        //getSomethingElse();
    });
},
getSomethingElse : function(){
}

我想在ajax 的done方法中调用getSomethingElse函数

使用$this=this;,因为函数中的this没有引用对象。

getSomething: function()
{
var $this = this;
var gotValue = sendAjax();
gotValue.done(function(response){
   console.log(response);
   $this.getSomethingElse();
});
},
getSomethingElse : function()
{
}

或者您可以使用$.proxy

gotValue.done($.proxy(function(response){
   console.log(response);
   this.getSomethingElse();
},this));

使用对当前上下文的引用:

getSomething: function () {
    var self = this;
    sendAjax().done(function (response) {
        self.getSomethingElse(response);
    });
    // or even shorter: sendAjax().done(self.getSomethingElse);
},
getSomethingElse: function () {}

使用绑定方法:

getSomething: function () {
    sendAjax().done(function (response) {
        this.getSomethingElse(response);
    }.bind(this));
},
getSomethingElse: function () {}

试试这个:

var someHelper = {
    getSomething : function() {
        var gotValue = sendAjax();
        //keep a reference to the obj, normally "this", or "someHelper" 
        var self = this; 
        gotValue.done(function(response) {
            console.log(response); //How to pass context of object to call getSomethingElse
            //getSomethingElse();
            //call getSomethingElse
            self.getSomethingElse();
        });
    },
    getSomethingElse : function() {
    }
}