[英]Jquery $.ajax Get response conflicting with nested passing of 'this' object to 'success' callback function
我试图做一个jQuery $.ajax
Get
类的方法内。 Get
请求提供的数据将在成功使用时在回调函数中使用,并且该类也需要在同一回调中进行修改。 所以,我不得不.apply
回调在this
标识的原始类的,因为否则,回调里面, this
是越来越局部更换。 但是在this
应用回调时, Get
返回的数据为undefined
。 我如何解决此问题。 任何帮助表示赞赏。
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
});
};
}
您可以在ajax配置中提供context
参数。 所有的Ajax回调将在上下文中调用(即this
回调中会参考你传递的价值context
在$.ajax()
调用):
SomeClass.prototype.methodName = function() {
$.ajax({
....
context: this // callbacks will be called with the same context that methodName() is running in
....
});
}
您需要.bind(this)
,而不是.apply(this)
。 bind
更改函数的this
指针,而apply
实际上在新上下文中运行该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.