【问题标题】:Consistent ordering of Ajax resultsAjax 结果的一致排序
【发布时间】:2016-02-09 10:08:14
【问题描述】:

我在 playframework 中运行 Coffeescript 代码,该代码基于多个 AJAX 查询构建表。

$ ->
    $.get "/queues", (queues) ->
        $.each queues, (index, queue) ->
            $.get "/queue/" + queue, (html) ->
                $("#queues").append $("<tr>").html html

/queues 返回队列名称列表。
/queue/name 返回描述队列 @9​​87654324@ 的 HTML。
#queues 是一个表格,我在其中显示该描述。

这一切都很好,但是由于查询是异步的,追加调用每次都以不同的顺序执行,这意味着每次查询运行时表内容都会随机重新排序。由于这是提供动态的当前状态,因此查询每三秒运行一次。

每次都以一致的顺序显示行的好方法是什么?我有index,所以我可以尝试将数据添加到该行,但如果第三个查询首先返回,将其添加到第三行将无法正常工作。

我对排序的完成方式没有强烈的偏好,只是在多次加载时它是一致的。

【问题讨论】:

    标签: ajax coffeescript playframework-2.4


    【解决方案1】:

    一种选择是强制查询是连续的。例如,定义一个递归函数来获取一个查询的结果,然后再进行下一个查询:

    do_queue = (index, queues) ->
        if index >= queues.length then return
        queue = queues[index]
        $.get "/queue/" + queue, (html) ->
            $("#queues").append $("<tr>").html html
            do_queue(index+1, queue)
    

    然后这样称呼它:

    $ ->
        $.get "/queues", (queues) ->
            do_queue(0, queues)
    

    【讨论】:

    • 优秀。这正是我所需要的。
    猜你喜欢
    • 2013-07-26
    • 1970-01-01
    • 2018-01-28
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    相关资源
    最近更新 更多