2012-01-21 144 views
0

我在我的應用程序中使用Backbone.js和jQuery 1.7,並且在構建集合時遇到了一些問題。在集合中我有方法,它應該返回一些對象。我在$ .ajax(...)success()函數中「返回」。我應該在哪裏返回聲明

在這種情況下,我收到「未定義」,而不是預期的對象。我明白,問題出在「返回」 - 它使success()函數返回一些值。但我需要getDomainZones()方法做一個返回。我該怎麼做?

window.DmnList = Backbone.Collection.extend({ 
     model: DmnItem, 
     localStorage: new Store("hosting.WhoIs"), 
     destroyAll: function (options) { 
      while (this.models.length > 0) { 
       this.models[0].destroy(options); 
      } 
     }, 
     getDomainZones: function(){ 
      $.ajax({ 
       url: 'http://hosting/rest/getDomains', 
       type: 'GET', 
       dataType: 'json', 
       cache: 'false', 
       timeout: 5000, 
       success: function(data) { 
        console.log(data); 
        return data;//problem here 
       }, 
       error: function(jqXHR, textStatus, errorThrown) { 
        console.log("Error[getDomainZones]: " + textStatus); 
        console.log(jqXHR); 
       }, 
      }); 
     } 
}); 
+1

一百萬份重複。所有的本地化都被標記爲重複。爾加! –

回答

3

當我應該把return語句」

無處。您不能返回異步 AJAX請求的結果。

依賴於data任何代碼,必須調用success回調。


一種可能是讓你getDomainZones方法收到在接收到響應時將調用的函數。

getDomainZones: function(callback){ 
    $.ajax({ 
     url: 'http://hosting/rest/getDomains', 
     type: 'GET', 
     dataType: 'json', 
     cache: 'false', 
     timeout: 5000, 

    // success: callback, // alternative if there's no other work to do. 
     success: function(data) { 
      console.log(data); 

      callback(data); // invoke the function received 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log("Error[getDomainZones]: " + textStatus); 
      console.log(jqXHR); 
     }, 
    }); 
} 

,那麼你會傳遞一個功能getDomainZones,並在接收到響應時,getDomainZones將調用您傳遞的功能,通過它的data

getDomainZones(function(d) { 
    // do something with the data 
    console.log(d); 
}); 
+0

「異步的異步JavaScript和XML」 –

+0

「AJAX」或「異步XMLHttpRequest」(更好) –

+0

是的,很好的解決方案。或者,使用承諾對象。 –

相關問題