Jquery:异步如何按顺序加载内容

时间:2016-02-14 09:45:27

标签: jquery hyperlink

我有一个带有以下jquery脚本的html页面。它使用$ .get来获取http://locahost,并在内部回调函数中附加一个到<pre>元素的链接。所有这一切都在一个循环内运行。循环运行100次,创建了100个链接。完成100个循环需要一些时间。同时,如果我想点击任何链接,它不允许点击。我正在寻找的是,当循环继续时,我应该能够点击它已经创建的链接。

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="https://localhost/~simha/viralvideos-master/js/jquery-2.1.3.min.js"></script>
</head>
<body>
<pre>   </pre>
<script>
    $.ajaxSetup({
        async: true
    });
    $(document).ready(function () {

        for (var i = 0; i < 100; i++) {
            console.log("b = " + i);
            fburl1 = "http://localhost/";
            console.log($('pre'));
            $.get(fburl1, function (data) {
                console.log("a = " + i);
                $('pre').append("<a href=\"localhost\">\"hare\""+i+"<a\/><p><\/p>");
            })
        }
    })
</script>
</body>
</html>

输出

"hare"100

"hare"100

"hare"100

"hare"100

"hare"100

"hare"100

"hare"100

"hare"100

我想要它

"hare"1

"hare"2
..

"hare"100

1 个答案:

答案 0 :(得分:2)

避免同步AJAX请求

原因(docs):

  

同步请求阻止执行创建&#34;冻结&#34;在屏幕上和无响应的用户体验。

因此,在您的情况下,删除以下设置应该会使其更好用:

$(document).ready(function() {

    for (var i = 0; i < 100; i++) {

        var fburl1 = "http://localhost/";

        // Create a closure with scoped i value passed as index inside
        (function(index) {
            $.get(fburl1, function(data) {
                console.log("a = " + index);
                $('pre').append("<a href=\"localhost\">\"hare\"" + index + "<a\/><p><\/p>");
            });
        })(i);
    }
})

<强> UPD 即可。您还可以对迭代索引进行范围调整,以使其对每次迭代都正确:

.encode()