Jquery ajax:传递范围来设置它

时间:2011-07-03 13:30:01

标签: javascript ajax jquery

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

  

Person = function(){

    this.__type = "PersonDto:#Empower.Service.Common.Dto";
    this.Name = undefined;
    this.Surname = undefined;

    this.GetById = function (id) {
        return $.ajax({
            type: "POST",
            url: "/Services/PersonService.svc/GetPersonById",
            data: JSON.stringify(id),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                ...
                this = data;
                ...
            }
        });
    }
};

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

提前感谢您的帮助,我为我糟糕的英语道歉

3 个答案:

答案 0 :(得分:5)

jQuery.ajax()[docs]方法为您提供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

        }
    });
}

答案 1 :(得分:1)

您不需要全局。

刚刚提出:

 var self = this;

紧接在return $.ajax(...)行之前,然后使用self引用AJAX回调函数中的当前实例。

此变量仅在GetById()函数范围内。

答案 2 :(得分:0)

当然,您可以将this放入变量,然后在回调中使用该变量

var self = this;

this.GetById = function (id) {
    return $.ajax({
        type: "POST",
        url: "/Services/PersonService.svc/GetPersonById",
        data: JSON.stringify(id),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            ...
            self = data;
            ...
        }
    });
}