[英]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.