Javascript - AJAX request inside loops

前端 未结 3 1738
日久生厌
日久生厌 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('
  • ' + data +'
  • '); totalQuotes++; } } domManipulation()

    JSFIDDLE

提交回复
热议问题