簡體   English   中英

jQuery $ .ajax獲取響應與將此對象嵌套傳遞給成功回調函數沖突

[英]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實際上在新上下文中運行該函數。

我覺得你的意思bindapply bind創建一個新函數,在設置this函數時調用包裝的函數; applyaddme()運行后立即調用該函數。

但是bind是ECMAScript第五版的功能,因此您需要執行以下一項操作:

  1. 適用於較舊瀏覽器的polyfill bind
  2. 使用jQuery等效proxy ;
  3. 使用context參數ajax ,它設置this明確;
  4. 記住var that= this; addme並在內部函數中使用附帶的that引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM