2013-02-06 25 views
0

我正在嘗試在$.when()內部進行jQuery AJAX調用,以便在進行回調時執行其他操作。但不幸的是,我沒有從我調用的方法獲得回調,這使得AJAX調用成功。以下是代碼...

/****** Code which calls the function ******/ 

var pathString = "/Cities?state=" + whichState; 

$.when(makeAJAXRequest(pathString)).done(function(data) 
{ 
    alert(data);     //Shows undefined 

    //Other operations ..... 
} 

/****** My function which makes the AJAX call ******/ 

function makeAJAXRequest(pathString) 
{ 

$.ajax({ 
     type:'GET', 
     async:'false', 
     cache:false, 
     url:'./proxy.php', 
     data:{path:pathString},   //Can put the query-string in the path. But if put in data attribute, it will work with both GET and POST 
     dataType:'xml', 
     success:function(data) 
     { 
    //alert(data); 

    return data; 
    }, 
    error:function(xhr, textStatus, errorThrown) 
    { 
    alert("Error in AJAX request: " + textStatus + errorThrown); 

    return ("Error in AJAX request: " + textStatus + errorThrown); 
    } 
}); 

} 

回答

0

的問題是,你真的不是在你的makeAjaxRequest()方法返回一個Deferred對象。

應該是這樣的:

function makeAJAXRequest(pathString) { 
    var deferred = new $.Deferred(); 
    $.ajax({ 
     type:'GET', 
     async:'false', 
     cache:false, 
     url:'./proxy.php', 
     data:{path:pathString} 
     dataType:'xml', 
     success:function(data) { 
      // Deferred object success 
      return deferred.resolve(data); 
     }, 
     error:function(xhr, textStatus, errorThrown) { 
      alert("Error in AJAX request: " + textStatus + errorThrown); 
      // Deferred object reject 
      return deferred.reject("Error in AJAX request: " + textStatus + errorThrown); 
     }); 
    return deferred.promise(); 
    } 

請大家在遞延文檔仔細一看:http://api.jquery.com/category/deferred-object/

+0

工作得很好。對於'錯誤'回調也是一個完美的解決方案。 –

+0

如果帖子確實解決了您的問題,則應將其標記爲已接受。乾杯! – ElHacker

+0

工作但它是很多額外的代碼,請參閱我的答案。 – wakooka