为什么SoundCloud API会导致循环以不同的顺序列出数据

时间:2014-06-26 00:39:32

标签: javascript jquery json loops soundcloud

我制作了一个JSON文件来存储SoundCloud网址。然后我的$.each()我加载JSON文件的数据,并根据数据从SoundCloud API收集更多数据。不知怎的,因为SoundCloud导致我的循环以随机顺序加载数据,而不是JSON文件中的数据。

以下是获取数据和SoundCloud位的代码:

$.getJSON("http://www.json-generator.com/api/json/get/bLjOHIYsAy?indent=2", function(data){ //Link of the playlist

$.each(data.PlayListArray, function(key, val){ //navigate to array called PlayListArray
     var songLink = val.URL; // the value of URL in the array
        SC.get('/resolve', { url: songLink }, function(track) { //convert SoundCloud URLs to ids to get their data.
        $("#demo").append("<p id= "+ track.id + ">" + track.title + "</p>");
        });

});
});

当我在循环中没有任何SoundCloud代码的情况下加载数据时,顺序是正确的。但是每次刷新页面时都会使用soundcloud,顺序也不同。请查看演示:http://jsfiddle.net/Fq2Rw/

在JSFiddle上,请运行代码copple,每次都会看到订单更改。这是为什么?任何的想法?或者通过JSON循环的任何不同方式?

1 个答案:

答案 0 :(得分:1)

您的代码循环遍历每个SC.get,但它不会等待SC.get完成。因此,每次重新加载时顺序都不同。

我会将其更改为使用SC.get的回调参数来加载下一个网址。


进一步思考,我建议使用jquery延迟函数来链接事件。

请看这篇文章: Soundcloud Javascript API SC.get() will not allow me to change a variable outside of the function