[英]Jquery $.ajax Get response conflicting with nested passing of 'this' object to 'success' callback function
I am trying to do a jquery $.ajax
Get
inside a method of a class. 我试图做一个jQuery
$.ajax
Get
类的方法内。 The data supplied by the Get
request to be used in the callback function on success and also the class needs to be modified inside the same callback. Get
请求提供的数据将在成功使用时在回调函数中使用,并且该类也需要在同一回调中进行修改。 So, I had to .apply
the callback on the this
identifier of the original class since otherwise ,inside the callback, this
was getting replaced locally. 所以,我不得不
.apply
回调在this
标识的原始类的,因为否则,回调里面, this
是越来越局部更换。 But while applying callback to this
the data returned by Get
is coming as undefined
. 但是在
this
应用回调时, Get
返回的数据为undefined
。 How do I work around this problem. 我如何解决此问题。 Any help appreciated.
任何帮助表示赞赏。
var tableblock = function(tablename){
this.tablename = tablename;
this.numusers = 0;
this.userpool = new Array();
this.addme = function(){
bodyContent = $.ajax({
type: "GET",
url: "controllers/bestpals.php",
data: "addpal=1&palname="+userid+"&nocache="+Math.floor((Math.random()*100)+1),
error: function(xhr, statusText){alert('could not add pal. refresh page.');},
success: function(msg){
alert(msg); // this will give undefined when .apply(this)
myid = msg;
syncpals(this,true);
}.apply(this) // using this alert(msg) above gives undefined
});
};
}
You can provide a context
parameter in your ajax configuration; 您可以在ajax配置中提供
context
参数。 all ajax callbacks will be called in that context (ie, this
inside the callback will refer to the value you pass as context
in your $.ajax()
call): 所有的Ajax回调将在上下文中调用(即
this
回调中会参考你传递的价值context
在$.ajax()
调用):
SomeClass.prototype.methodName = function() {
$.ajax({
....
context: this // callbacks will be called with the same context that methodName() is running in
....
});
}
You want .bind(this)
, not .apply(this)
. 您需要
.bind(this)
,而不是.apply(this)
。 bind
changes the this
pointer of a function, while apply
actually runs the function in the new context. bind
更改函数的this
指针,而apply
实际上在新上下文中运行该函数。
I think you meant bind
not apply
. 我觉得你的意思
bind
不apply
。 bind
creates a new function that calls the wrapped one whilst setting this
; bind
创建一个新函数,在设置this
函数时调用包装的函数; apply
calls the function straight away as soon as addme()
runs. apply
在addme()
运行后立即调用该函数。
However bind
is an ECMAScript Fifth Edition feature, so you'd need to do one of: 但是
bind
是ECMAScript第五版的功能,因此您需要执行以下一项操作:
bind
for older browsers; bind
; proxy
; proxy
; context
argument to ajax
, which sets this
explicitly; context
参数ajax
,它设置this
明确; var that= this;
var that= this;
in addme
and use the enclosed that
reference in the inner function. addme
并在内部函数中使用附带的that
引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.