2012-03-11 121 views
1

如果我有對象myApiexecute功能jQuery的AJAX聽衆

var api = new myApi(); 
api.execute(); 

裏面execute我有(* thatmyApi實例)

function execute() { 
     $.ajax({ 
      type: this.getRequestMethod(), 
      data: this.getDataParams(), 
      complete: function(xmlHttp){ 
       that.setResult(jQuery.parseJSON(xmlHttp.responseText)); 
       that.setHttpStatus(xmlHttp.status); 
      }, 
      url: this.getUrl(), 
      beforeSend: setHeader 
     }); 
    } 

我怎樣才能使回調/監聽器,所以我可以做此

var api = new myApi(); 
api.execute(); 
var result = api.getResult(); 
var statusCode = api.getStatusCode(); 
switch(statusCode) {...}; 

如果我以這種方式離開它,這些底部兩行在ajax調用完成之前執行(complete尚未調用),因此我有undefined變量。

回答

1

你不能這樣做,除非你強制AJAX請求是同步的(這可能是一個壞主意)。你需要附加一些回調方法,你也可以使用一些jQuery Deferred魔法。

因此,返回jqXHR對象,它封裝了Deferred

function execute() { 
    return $.ajax({ 
     type: this.getRequestMethod(), 
     data: this.getDataParams(), 
     complete: function(xmlHttp){ 
      that.setResult(jQuery.parseJSON(xmlHttp.responseText)); 
      that.setHttpStatus(xmlHttp.status); 
     }, 
     url: this.getUrl(), 
     beforeSend: setHeader 
    }); 
} 

,然後用它像

var api = new myApi(); 
var req = api.execute(); 
req.done(function(data) { 

}); 
req.fail(function(xhr) { 
    var statusCode = xhr.status; // etc. 
});