2012-11-06 86 views
0

我在我的html中有一個選擇,並希望在頁面加載時通過ajax添加選項。選項值在我的數據庫中,我通過調用ajax獲取它們。爲此,我正在使用JavaScript編寫一個類,但運行時無法獲取數據。請看看:在jquery中訪問類變量

--- Main.js ---

function MyLoader() { 
    this._clients = null; 
    this._code = null; 
} 

Loader.prototype = { 

    var context = this; 

    loadClients: function() { 
     $.ajax({ 
      url: "my/php/", 
      type: "POST", 
      data: {...}, 
      success: function(response) { 
       context._clients = response; 
      } 
     }); 
    }, 

    getCode: function() {...} 
}; 

然後,我有以下幾點:

$(document).ready(function() { 
    var loader = new Loader(); 
    loader.loadClients(); 
    alert(loader._clients); 

    //Here I want to add my options to the select 
}); 

我的警報始終返回null,我不明白爲什麼。我需要將我的數據保存在課程中,以便在需要時隨時訪問它們。

你能指點我的方向嗎?謝謝您的回答。

回答

1
Loader.prototype = { //  v---callback parameter 
    loadClients: function(callback) { 
     $.ajax({ 
      url: "my/php/", 
      context: this, // <---set success context 
      type: "POST", 
      data: {...}, 
      success: callback // <---pass callback 
     }); 
    }, 

    getCode: function() {...} 
}; 

$(document).ready(function() { 
    var loader = new Loader(); 
         // v---pass callback 
    loader.loadClients(function(response) { 
     this._clients = response; 
     alert(this._clients); 
     //Here I want to add my options to the select 
    }); 

}); 
+0

謝謝!它工作正常:) – user1671731

0

我相信你需要在'成功'回調中完成所有動態加載,因爲它是異步加載的。

0

你需要做的成功回調裏面,因爲它是異步:

Loader.prototype = { 

    var context = this; 

    loadClients: function() { 
     $.ajax({ 
      url: "my/php/", 
      type: "POST", 
      data: {...}, 
      success: function(response) { 
       context._clients = response; 
       alert(loader._clients); 

       //Here I want to add my options to the select 
      } 
     }); 
    }, 

    getCode: function() {...} 
}; 

$(document).ready(function() { 
    var loader = new Loader(); 
    loader.loadClients(); 
});