Javascript - AJAX request inside loops

前端 未结 3 1726
日久生厌
日久生厌 2020-12-05 11:55

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 ha

相关标签:
3条回答
  • 2020-12-05 12:19

    You can use ES6 async/await Promises like this

    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

    0 讨论(0)
  • 2020-12-05 12:28

    Very interesting methods provided by jQuery when you are executing loops of asyncroniouse request and detect all ajax request completed or not. It is possible by using

    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);
    });
    

    Here $.when provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.

    apply() converts array elements as different arguments in function

    $.done is call function after all async. request are completed.

    0 讨论(0)
  • 2020-12-05 12:38

    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

    0 讨论(0)
提交回复
热议问题