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

时间:2010-10-05 12:20:09

标签: 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);
    }
}

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

1 个答案:

答案 0 :(得分:77)

使用context option,如下所示:

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

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