我有这个带有这个ajax调用的类:



在 ajax 调用成功后,我想设置 person 的当前实例,但是“this”不是设置的正确范围。
有比使用全局变量更优雅的方法吗?

预先感谢您的帮助,我为我的英语不好而道歉

最佳答案

jQuery.ajax() 方法为您提供了一个 context 属性,您可以在其中设置回调中 this 的值。

做就是了:

context: this,

...在您的通话中,例如:
this.GetById = function (id) {
    return $.ajax({
        type: "POST",
        context: this,  // <---- context property to set "this" in the callbacks
        url: "/Services/PersonService.svc/GetPersonById",
        data: JSON.stringify(id),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {

             // in here, "this" will be the same as in your "getById" method

        }
    });
}

关于javascript - jquery ajax : pass the scope to set it,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6563169/

10-11 05:09
查看更多