使用Javascript - 循环中的AJAX请求 [英] Javascript - AJAX request inside loops

查看:151
本文介绍了使用Javascript - 循环中的AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery发送一个AJAX请求,从服务器获取数据。

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

这数据被附加给一个元素。这应该发生5次,但它会总是发生随机要么3,4或5次。基本上有时循环将跳过AJAX请求,但大部分时间抓到它。我如何确保它完成请求,每次五次? (旁注。我已经检查请求的错误,但它从来没有惊动的请求失败)

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? (side note. I've checked the request errors, but it never alerted of a request failure)

这是我的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。出现这种情况的一个按钮preSS。

P.s. this happens on a button press.

推荐答案

不同步做。使用回调。这里是一个演示给你: http://jsfiddle.net/s368a/1/

Don't do it synchronously. Use the callback. Here is a demo for you: http://jsfiddle.net/s368a/1/

<ul class="quoteList"></ul>
<input type="button" onclick="getData();" value="Go Get It!">

<script>
var counter = 0;

function getData()
{
    $.ajax({
        url:'http://whisperingforest.org/js/getQuote.php',
        async: true,
        dataType: 'jsonp',
        success:function(data){
            $('.quoteList').append('<li>' + data +'</li>');
            counter++;
            if (counter < 5) getData();
        }
    });
}
</script>

设置异步假块主线程(负责执行的JavaScript,呈现在屏幕等),并等待XHR完成。

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

这是几乎总是一个可怕的想法。用户不喜欢没有响应的用户界面。 (<一href="http://stackoverflow.com/a/20209180/3112803">http://stackoverflow.com/a/20209180/3112803)

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

只要搜索计算器的 AJAX异步:假,你会发现这么多很好的解释。每个人都和他们的兄弟与鼓励你使用异步:假。这里是一个很好的解释:<一href="http://stackoverflow.com/a/14220323/3112803">http://stackoverflow.com/a/14220323/3112803

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

这篇关于使用Javascript - 循环中的AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆