Javascript - 循环中的AJAX请求

pas*_*NOR 11 javascript ajax jquery

我正在使用jQuery发送AJAX请求,从服务器检索数据.

然后将该数据附加到元素.这应该发生5次,但总是随机发生3次,4次或5次.基本上,有时循环会跳过AJAX请求,但大部分时间它都会捕获它.我如何确保每次完成请求五次?以及跳过AJAX请求的随机行为背后的原因是什么?(旁注.我检查了请求错误,但它从未提醒过请求失败)

这是我的JS:

while (counter < 6) {
    $.ajax({
        url:'http://whisperingforest.org/js/getQuote.php',
        async: false,
        dataType: 'jsonp',
        success:function(data){
            $('.quoteList').append('<li>' + data +'</li>');
            totalQuotes++;
        }
    });
    counter++;
}
Run Code Online (Sandbox Code Playgroud)

Ps会在按下按钮时发生.

gfr*_*ius 29

不要同步这样做.使用回调.这是一个演示:http://jsfiddle.net/y45Lfupw/4/

<ul class="quoteList"></ul>
<input type="button" onclick="getData();" value="Go Get It!">

<script>
var counter = 0;

window.getData=function()
{
    /* This IF block has nothing to do with the OP. It just resets everything so the demo can be ran more than once. */
    if (counter===5) {
        $('.quoteList').empty();
        counter = 0;
    }

    $.ajax({
        /* The whisperingforest.org URL is not longer valid, I found a new one that is similar... */
        url:'http://quotes.stormconsultancy.co.uk/random.json',
        async: true,
        dataType: 'jsonp',
        success:function(data){
            $('.quoteList').append('<li>' + data.quote +'</li>');
            counter++;
            if (counter < 5) getData();
        }
    });
}
</script>
Run Code Online (Sandbox Code Playgroud)

设置async为false会阻止主线程(负责执行JavaScript,呈现屏幕等)并等待XHR完成.

这几乎总是一个糟糕的主意.用户不喜欢无响应的UI.(/sf/answers/1414642631/)

只需搜索stackoverflow ajax async: false,您就会发现很多很好的解释.每个人都会阻止你使用async:false.这是一个很好的解释:https://stackoverflow.com/a/14220323/3112803


Har*_*dja 7

当您执行asyncroniouse请求的循环并检测所有ajax请求是否已完成时,jQuery提供了非常有趣的方法.可以通过使用

var users=["a","b","c","d","e","f","g","h"];

var async_request=[];
var responses=[];
for(i in users)
{
    // you can push  any aysnc method handler
    async_request.push($.ajax({
        url:'', // your url
        method:'post', // method GET or POST
        data:{user_name: users[i]},
        success: function(data){
            console.log('success of ajax response')
            responses.push(data);
        }
    }));
}


$.when.apply(null, async_request).done( function(){
    // all done
    console.log('all request completed')
    console.log(responses);
});
Run Code Online (Sandbox Code Playgroud)

这里$ .when提供了一种基于零个或多个对象执行回调函数的方法,通常是表示异步事件的Deferred对象.

apply() 将数组元素转换为函数中的不同参数

所有异步后,$ .done都是调用函数.请求已完成.