2012-03-11 109 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. 
});