1

I first get a JSON playlist of videos. I then get JSON information on each video id that was provided in the playlist. From each video information JSON I want to list the video's thumbnail url in the "#container" div.

My issue is that the order of thumbnails changes every time I hit the "Get JSON data" button. I looked in the console and the individual video JSON is always queried in the same order, it's just that when I post information from that JSON it's not in order.

What gives?

$(document).ready(function(){
  $("button").click(function(){
    //$('p').remove();
        $.getJSON("https://api.dailymotion.com/playlist/xy4h8/videos",function(result){

            $.each(result.list, function (index, value) {
            //  console.log(value.id); 
                $.getJSON("https://api.dailymotion.com/video/"+value.id+"?fields=id,title,thumbnail_medium_url",function(resulted){
                    $("#container").append(resulted.thumbnail_medium_url + "<br />"); // THIS IS THE BIT ALWAYS OUT OF ORDER
                }); // use id of each object in list to get next json
            }); // for each of the list object within the playlist result obj

        }); // get playlist json
    }); // button click
});

Thanks for any help.

4

2 回答 2

0

这是因为在每个循环中,您正在进行 ajax 调用。所以所有请求几乎同时进行。并且根据每个 ajax 调用所花费的响应时间,值会附加到容器上。因此,谁的响应将首先出现,它将首先添加。这就是为什么顺序总是不同的原因。

如果您想要每次相同的订单,请将您的所有 ajax 请求排队。这可以帮助您将所有 ajax 请求保留在队列中。请参阅第三个示例“排队类似 Ajax 调用” http://learn.jquery.com/effects/uses-of-queue-and-dequeue/

于 2013-05-22T03:26:32.790 回答
0

$.getJSON()函数只是数据类型设置为的函数的快捷方式。如果您查看jQuery.ajax() 函数的文档,您会看到它默认设置为异步,这意味着它可能随时发生,并且可能没有指定的顺序。您可以通过使用和做一个直线来解决这个问题。$.ajax()jsonjQuery.ajax()async: falsedataType: 'json'

于 2013-05-22T03:34:56.103 回答