首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用多个ajax调用成功填充html表

使用多个ajax调用成功填充html表
EN

Stack Overflow用户
提问于 2017-02-22 03:21:28
回答 1查看 1.1K关注 0票数 1

我正在使用ajax api调用来填充html表。表的第一列是The (item.name),我嵌套了第二个ajax调用,以便用日期填充第二列(顺便说一句,日期是从纪元开始以微秒为单位返回的……我将在稍后对此进行格式化)。我嵌套的原因是因为第二个调用使用了url中第一个调用的部分结果。代码如下:

HTML

代码语言:javascript
运行
复制
<div id="output">
    <table id="scalaapi">
    <tbody>
    <tr><td></td><td class="uuid"></td></tr>
    </tbody>
    </table>
</div>

AJAX

代码语言:javascript
运行
复制
$.ajax({
type: 'GET',
url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/players?offset=0&sort=name&filters=%7BplayerStatus%20:%20%7Bvalues:%5B'HEARTBEAT_OVERDUE'%5D,%20comparator%20:%20'eq'%7D%7D",
dataType: "json",
success: function(data) {
var list = data.list;
$.each(list, function(i, item) {
var tr = $('<tr>').append('<td>' + (item.name) + '</td>' + '<td>'+ 
    $.ajax({
    type: 'GET',
    url: "https://avacmd25.scala.com:44335/ContentManager/api/rest/heartbeats/sequence/"+(item.uuid),
    dataType: "text",
    crossDomain: true,
    success: $.each(function(results) { 
                $('.uuid').text(results);
            })
    })
    + '</td>');
$("#scalaapi").append(tr);
});
}
})

我得到的结果好坏参半。第一个api调用按预期工作,尽管它跳过了第一行。第二个api调用仅返回第一条记录,并且没有跳过第一行,随后的行将显示object对象

结果屏幕截图-

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-22 04:04:57

您在代码中执行了大量操作,无需等待AJAX调用完成,即可立即执行操作。试着让你的javascript更有耐心一点(下面是伪代码,我去掉了大部分额外的AJAX配置内容,希望能让代码做得更清楚):

代码语言:javascript
运行
复制
$.ajax({..., success: function(data) {
    // when we get here the first AJAX call has returned

    // loop through each item in the response from the first AJAX call
    $.each(data.list, function(i, item) {
        // append the <tr> to the table with the information we have for the item and a placeholder for the second cell
        var tr = $('<tr><td>'+item.name+'</td><td class="uuid">...</td></tr>').appendTo('#scalaapi');

        // make the second AJAX call for this item
        $.ajax({
            url:".../sequence/"+item.uuid,
            ...,
            success: function(result) {
                // we now have the contents we need for the second <td>, so insert it
                tr.find('.uuid').text(result);
            }
         });
    });
});

我相信这会让你更接近你想要做的事情?

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42376126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档