2012-01-21 80 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

是的,很好的解决方案。或者,使用承诺对象。 –