Javascript - AJAX请求内循环

Javascript - AJAX request inside loops

本文关键字:循环 请求 AJAX Javascript      更新时间:2023-09-26

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

然后将该数据附加到元素中。这应该发生5次,但它总是随机发生3、4或5次。基本上,有时循环会跳过AJAX请求,但大多数情况下它会捕获它。我如何确保它每次都能完成5次请求?跳过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++;
}

注。

不要同步进行。使用回调。下面是一个演示: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>

设置async为false会阻塞主线程执行JavaScript、呈现屏幕等),然后等待XHR完成。

这几乎总是一个糟糕的主意。用户不喜欢无响应ui。(https://stackoverflow.com/a/20209180/3112803)

在stackoverflow上搜索ajax async: false,你会发现很多很好的解释。每个人都会劝阻你不要使用async:false。这里有一个很好的解释:https://stackoverflow.com/a/14220323/3112803

当您执行异步请求循环并检测所有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);
});

美元。When提供了一种基于零执行回调函数的方法或更多对象,通常是表示异步的Deferred对象事件。

apply()将数组元素转换为函数

$。完成是调用函数后,所有异步。请求是完成。

你可以像这样使用ES6 async/await promise

function fromServer(){
  return new Promise((resolve, reject) => {
     $.ajax({
        url:'http://whisperingforest.org/js/getQuote.php',
        async: false,
        dataType: 'jsonp',
        success:function(data){
             resolve(data)
        }
    });
  })
}
var totalQuotes = 0;
async function domManipulation(){
    while (counter < 6) {
        var data = await fromServer();
        $('.quoteList').append('<li>' + data +'</li>');
        totalQuotes++;
    }
}
domManipulation()

JSFIDDLE