如何在jQuery AJAX成功回调函数中传递上下文(context)

52
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对象。如何将Box对象传递到exeSuccess方法中?

1个回答

81

使用context选项,如下所示:

    $.ajax({
        context: this,
        type: "post",
        url: "some url",
        success: this.exeSuccess,
        error: this.exeError,
        complete: this.exeComplete
    });
选项决定了回调函数被调用时的上下文环境,因此它决定了该函数内this指向的是什么。

3
非常抱歉。忽略了jQuery文档。这里清楚地提到了http://api.jquery.com/jQuery.ajax/。 - rajakvk
5
或许已经提到了,但如何使用并不是十分清楚。尼克的例子非常有帮助。这篇文章提供了更详细的信息:https://dev59.com/cm435IYBdhLWcg3w-1Z_ - Software Prophets

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接