jQuery的阿贾克斯:如何要等到*异步*请求成功,然后再继续完成? [英] jQuery Ajax: how to wait until *async* requests success completes before continuing?

查看:203
本文介绍了jQuery的阿贾克斯:如何要等到*异步*请求成功,然后再继续完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,使AJAX快速的的功能。这里的伪/原型code:

I'm having a problem making ajax fast and functional. Here's the pseudo/prototype code:

function blah1(arg1){//arg1 is an array, roughly 10 elements

var arr[];

$.each(arg1, function(i){
//blah code

    $.ajax({
        //blah options
        async:   true,
        success: function(data){
            arr[i] = data.someInt;
        }//end success
    });//end ajax
}//end each

return arr;
}//end function

基本上,我送一个AJAX,需要返回的数据进行进一步的处理。

Basically, I'm sending an ajax and need the returned data for further processing.

如果我设置异步为true,则函数立即返回空'改编'阵,因此,整个脚本失败。 但是,如果我设置异步为false,那么它的工作原理,但需要很长时间。

If I set async to true, the function immediately returns empty 'arr' array, thus the whole script fails. But if I set async to false, then it works, but takes very long.

我已经看到了这<一href="http://stackoverflow.com/questions/3034874/sequencing-ajax-requests/3035268#3035268">$.ajaxQueue();的事情,但坦白说,我不理解的事,我不知道这是否正常工作。

I have seen this $.ajaxQueue(); thing, but frankly I don't understand it at all, and I don't know if it will work.

所以现在的问题是,首先,有没有什么办法,我可以异步发送,同时所有的Ajax请求,并让功能等,并返回ARR []所有的Ajax完成后?如果没有,在我的情况下,ajaxQueue工作? (粗略的例子吗?)

So the question is, firstly, is there any way I can asynchronously send all the ajax requests at the same time and let function wait and return arr[] after all ajax are done? If not, will the ajaxQueue work in my case? (rough example please?)

推荐答案

使用jQuery 1.5推迟的我会选择这样的:

Using jQuery 1.5 deferred's I would opt for this :

function blah1(arr, callback){
    $.when($.map(arr, function(val, i){
        $.ajax({
            //blah options
            async:   true
        });
    }).toArray()).then(function(resultsArr) {
         callback(resultsArr);
    });
}

但问题是你想异步Ajax调用完成,然后返回数组中的作用。这是不是真的有可能,所以你需要一个回调传给等等。

The problem was you were trying to return the array in your function before the async ajax calls finish. This isn't really possible so you will need to pass a callback to blah.

你做什么这里是映射你的对象jqXHR对象(被延迟的对象)的数组。然后通过延迟对象的数组 $。当

What your doing here is mapping your array of objects to jqXHR objects (which are deferred objects). Then passing that array of deferred objects to $.when.

$。当以一个数组,然后允许您运行。然后功能时,整个阵列完成了从Ajax调用加载。那么你有一个 resultsArr 传递作为参数传递到你的。然后功能。

$.when takes an array and then allows you to run the .then function when the entire array has finished loading from the ajax calls. You then have a resultsArr passed in as an argument to your .then function.

有没有办法使用 $。阿贾克斯返回在相同的功能,如果你操作的返回值在阿贾克斯成功的呼叫。

There is no way to use $.ajax and return in the same function if you manipulate the return value in your ajax success call.

这篇关于jQuery的阿贾克斯:如何要等到*异步*请求成功,然后再继续完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆