Erm*_*lla 3 javascript ajax jquery
我有这个带有这个ajax调用的类:
Person = function(){
Run Code Online (Sandbox Code Playgroud)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"对于设置不是正确的范围.有一种比使用全局变量更优雅的方式吗?
提前感谢您的帮助,我为我糟糕的英语道歉
在jQuery.ajax()[文档]方法给你一个context属性,您可以设置的值this的回调.
做就是了:
context: this,
Run Code Online (Sandbox Code Playgroud)
......在你的电话中,如:
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
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2600 次 |
| 最近记录: |