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

raj*_*kvk 49 javascript jquery

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*ver 77

使用context选项,如下所示:

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

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

  • 也许有明确提到,但不清楚如何使用它.尼克的例子非常有帮助.这篇文章更详细:http://stackoverflow.com/questions/5097191/ajax-context-option (4认同)
  • 非常抱歉.过度看见的jQuery文档.这里明确提到http://api.jquery.com/jQuery.ajax/ (3认同)