5

我必须在一个循环中发出一系列 Ajax 请求。其中大约100个。每个请求都返回一个 JSONP 变量。我从 JSON 中提取数据并继续将值附加到 div 中。问题是我希望 div 按函数调用的顺序附加数据。即顺序。现在,每次刷新页面时,我都会根据请求完成的顺序获得不同的顺序。这是我的代码。

  $.each(elem, function (index, item) {

            $.ajax({
                type: 'post' ,
                url: moviesSearchUrl + '&q=' + encodeURI(item) + '&page_limit=1',
                dataType: "jsonp",
                async: false, 
                success: searchCallback
            });

            function searchCallback(data) {
                var movies = data.movies;

                var markup = index + ': '+   movies[0].title + '<img class=" bord" src="' + movies[0].posters.thumbnail + '" /><br/>';

                $("div.content").append(markup);
            }

        });
});

当我在 div 内显示索引的值时,每次我得到随机订单。2 4 3 1 7 有时和 1 5 2 7 4 有时。我什至尝试 async: false 。那没有帮助。我在某处读到 JSONP 不能用 async: false 完成。请帮帮我。

4

4 回答 4

9

不要使用 for 循环。使用递归函数:

var i = 1;

function loadNext(){
    if (i < 5){
        $.ajax({
            type: "GET",
            url: "results/result_html.php?usn="+i+"&resultType="+resultType,
            dataType:"JSON",
            success:function(result){
                finalResult+=result;
                result=result+htmlMessage;
                $("#info").hide();
                $("#result").html(result);              
                $("#usn").attr("placeholder", "Class USN");
                loadNext();
            }
        });
        i++;
    }
}
于 2013-12-21T06:39:55.747 回答
4

您可以使用占位符。

  $.each(elem, function (index, item) {

            var $placeholder = $('<div>').appendTo("div.content");

            $.ajax({
                type: 'post' ,
                url: moviesSearchUrl + '&q=' + encodeURI(item) + '&page_limit=1',
                dataType: "jsonp",
                async: false, 
                success: searchCallback
            });

            function searchCallback(data) {
                var movies = data.movies;

                var markup = index + ': '+   movies[0].title + '<img class=" bord" src="' + movies[0].posters.thumbnail + '" /><br/>';

                $placeholder.replaceWith(markup);
            }

        });
});
于 2012-04-11T02:01:27.140 回答
2

就像是:

// iterate over your set
$.each(myset, function(i,e){

  // placeholder div (hidden from view until it's populated)
  var $placeholder = $('<div>').hide().appendTo('div.content');

  // make your ajax call
  $.getJSON('/link/to/resource','{date:here}',function(d){

    // insert the content in to the div and re-show it
    $placeholder.text(i + ': ' + d.movies[0].title).show();
  });
});
于 2012-04-11T02:05:49.257 回答
0

    const j = 10;
    for (let i = 1; i <= j; i++) {
        // wait for the promise to resolve before advancing the for loop
        await ajaxcall(i);
        console.log(i);
    }
}

function ajaxcall(id){
   return new Promise(function(resolve, reject){
      var sUrl = "https://jsonplaceholder.typicode.com/todos/"+id;

      $.get(sUrl, function(data) {
           alert( "Load was performed."+JSON.stringify(data));
           resolve(data); 
      });
      
   }); 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button onclick="someFunction()"> Test </button>

于 2018-11-29T08:22:37.073 回答