【问题标题】:Why does SoundCloud API cause the loop to list data in different orders为什么 SoundCloud API 会导致循环以不同的顺序列出数据
【发布时间】:2014-06-26 00:39:31
【问题描述】:

我制作了一个 JSON 文件来存储 SoundCloud URL。然后我的$.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 上,请多次运行代码,每次都会看到顺序变化。这是为什么?任何的想法?或者有什么不同的方式来循环 JSON?

【问题讨论】:

    标签: javascript jquery json loops soundcloud


    【解决方案1】:

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

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


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

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

    【讨论】:

    • 感谢您的帖子。你的意思是我必须创建一个 SC.get 函数并在每次查看时调用它?如果不能,请您通过代码显示它。谢谢
    • 我厌倦了按照你的建议使用回调,不确定我是否正确使用它,但是它没有显示数据这是演示:http://jsfiddle.net/Fq2Rw/4/。关于延迟方法,我无法弄清楚它是如何工作的。看起来好复杂。
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多