执行异步操作后执行功能

时间:2011-12-01 11:56:59

标签: javascript jquery asynchronous

我遇到了一些问题,因为我正在尝试在我的应用程序的其他部分重用代码(可以使用)。

现在,我有了共同点:

$.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 个答案:

答案 0 :(得分:2)

使用隐式混合到jXHR对象中的jQuerys Deferred个对象。因此,您需要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/

答案 1 :(得分:-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()。