Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

jquery - Javascript - AJAX request inside loops

I'm using jQuery to send an AJAX request, retrieving data from a server.

That data is then appended to an element. This should happen 5 times, but it will always happen randomly either 3, 4, or 5 times. Basically, sometimes the loop will skip the AJAX request, but the majority of the time it catches it. How do I make sure it completes the request five times every time? and what is the reason behind this random behavior of skipping AJAX request?(side note. I've checked the request errors, but it never alerted of a request failure)

Here's my 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++;
}

P.s. this happens on a button press.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't do it synchronously. Use the callback. Here is a demo for you: 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>

Setting async to false blocks the main thread (responsible for executing JavaScript, rendering the screen, etc) and waits for the XHR to complete.

This is almost always a terrible idea. Users don't like unresponsive UIs. (https://stackoverflow.com/a/20209180/3112803)

Just search stackoverflow for ajax async: false and you will find MANY good explanations on this. Everyone will discourage you from using async:false. Here's is a great explanation: https://stackoverflow.com/a/14220323/3112803


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...