2011-12-01 68 views
1

我遇到了一些問題,因爲我試圖在應用程序的其他部分重新使用代碼(可以使用它)。現在執行異步操作後執行功能

,我有共同的:

$.ajax({ 
    url: JSONurl, 
    dataType: "json", 
    cache: false, 
    data: params, 
    success: function(data){ 
     // do stuff after the result is retrieved 
    } 
}); 

的東西會很好,但我想要做這樣的事情:

function ultramegafunction(){ 
    var ajax_data = asyncAjaxFunction(); 
    // When ajax_data is filled do other stuff 
} 

這樣一來,我可以使用asyncAjaxFunction()在不需要重寫所有代碼並在成功部分放置特定事物的其他功能。

有人知道我該怎麼做?

回答

2

使用jQuerys Deferred隱式混合到jXHR對象中的對象。因此,您需要return jXHR對象,然後在其他地方綁定處理程序。

function asyncAjaxFunction() { 
    return $.ajax({ 
     url: JSONurl, 
     dataType: "json", 
     cache: false, 
     data: params, 
     success: function(data){ 
      // do stuff after the result is retrieved 
     } 
    }); 
} 

和其他地方

function ultramegafunction(){ 
    asyncAjaxFunction().done(function(ajaxData) { 
     // When ajax_data is filled do other stuff 
    }); 
} 

參考:http://api.jquery.com/category/deferred-object/

+0

+1這是做它的方式 – Alnitak

+0

數據存儲在哪裏? –

+0

@AntonioLaguna:不知道問題是什麼,但ajax請求的結果也傳遞給'done()'處理程序。我在上面的代碼片段中給它命名了'ajaxData'。 – jAndy

-1

嘗試......

"asyncAjaxFunction" = function(options){ 
    var xhr = $.ajax({ 
     'url' : options.url, 
     'dataType' : (options.dataType) ? options.dataType : 'JSON', 
     'type' : (options.type) ? options.type : 'GET', 
     'async' : (options.async) ? options.async : false, 
     'data' : (options.data) ? options.data : '', 
     'cache' : (options.cache) ? options.cache : false, 
     'success' : (options.success)? (options.success) :function(data) { 
     }, 
     'error' : (options.error)? (options.error) :function() { 
     } 
    }); 
    return (xhr.status === 200) ? xhr.responseText : ''; 

} 

現在您就可以用適當的參數上任何地方撥打asyncAjaxFunction() 。