jquery - Javascript - AJAX request inside loops -
i'm using jquery send ajax request, retrieving data server.
that data appended element. should happen 5 times, happen randomly either 3, 4, or 5 times. basically, loop skip ajax request, majority of time catches it. how make sure completes request 5 times every time? , reason behind random behavior of skipping ajax request?(side note. i've checked request errors, never alerted of request failure)
here's 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. happens on button press.
don't synchronously. use callback. here demo you: http://jsfiddle.net/y45lfupw/4/
<ul class="quotelist"></ul> <input type="button" onclick="getdata();" value="go it!"> <script> var counter = 0; window.getdata=function() { /* if block has nothing op. resets demo can ran more once. */ if (counter===5) { $('.quotelist').empty(); counter = 0; } $.ajax({ /* whisperingforest.org url not longer valid, found new 1 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
false blocks main thread (responsible executing javascript, rendering screen, etc) , waits xhr complete.this terrible idea. users don't unresponsive uis. (https://stackoverflow.com/a/20209180/3112803)
just search stackoverflow ajax async: false
, find many explanations on this. discourage using async:false
. here's great explanation: https://stackoverflow.com/a/14220323/3112803
Comments
Post a Comment