javascript-如何在jquery ajax成功回调函数中传递上下文

var Box = function(){
    this.parm = {name:"rajakvk",year:2010};
    Box.prototype.jspCall = function() {
        $.ajax({
            type: "post",
            url: "some url",
            success: this.exeSuccess,
            error: this.exeError,
            complete: this.exeComplete
        });
    }
    this.exeSuccess = function(){
        alert(this.parm.name);
    }
}

我没有在exeSuccess方法中获取Box对象。 如何在exeSuccess方法内传递Box对象?

rajakvk asked 2020-02-29T11:44:31Z
1个解决方案
77 votes

使用this选项,如下所示:

    $.ajax({
        context: this,
        type: "post",
        url: "some url",
        success: this.exeSuccess,
        error: this.exeError,
        complete: this.exeComplete
    });

context选项确定了调用回调所使用的上下文...因此它确定了该函数内部this所引用的内容。

Nick Craver answered 2020-02-29T11:44:50Z
translate from https://stackoverflow.com:/questions/3863536/how-to-pass-context-in-jquery-ajax-success-callback-function