jQuery - 刷新getJson调用

时间:2014-01-30 18:33:17

标签: javascript jquery

好的,所以我使用下面的JS来查询API并填充表格。根据我在成功函数中循环的每次迭代上看到的另一篇文章,它构建了一个数组,然后将它连接到jQuery中并将其作为一行添加到表中。这很酷:

   // get the JSON from the API
    $.getJSON( "helpers.php", {
        func: "results",
        days: "3",
    })
    .done(function( rows ) {
        $.each(rows, function() {
            // populate the table
            var r = new Array(), j = -1;
            var matchDate = this.date;
                r[++j] = '<tr>';
                r[++j] = '<td><small>' + this.teamname; + '</small></td>';
                r[++j] = '<td>' + this.teamscore; + '</td>';
                r[++j] = '</tr>';
            $('#table-results').append(r.join('')); 
        });
    });

我想做的是每隔3秒调用一次。所以我想我会把我的getJson调用包装在setInterval函数中:

setInterval(function(){
    // get the JSON from the API
    $.getJSON( "helpers.php", {
        func: "results",
        days: "3",
    })
    .done(function( rows ) {
        $.each(rows, function() {
            // populate the table
            var r = new Array(), j = -1;
            var matchDate = this.date;
                r[++j] = '<tr>';
                r[++j] = '<td><small>' + this.teamname; + '</small></td>';
                r[++j] = '<td>' + this.teamscore; + '</td>';
                r[++j] = '</tr>';
            $('#table-results').append(r.join('')); 
        });
    });
},3000);

然而,这显然会继续'追加'行。我希望它像表刷新一样,所以它基本上会再次启动表。如果我不一定知道桌子的长度,我怎么能这样做呢?

1 个答案:

答案 0 :(得分:0)

首先,您应该考虑在此使用setTimeout而不是setInterval,并在您的成功方法中再次调用它。如果您的请求持续时间超过间隔,则在第一个请求完成之前再次执行请求,这可能会产生意外结果。我喜欢关于这个主题的article from JavaScript Garden

要刷新表而不闪烁,您应该在成功方法中重新填充表之前清空表。最流畅的方法可能是,如果您为行分配ID,并且实际上只更新行而不是整个表。

以下是一个例子:

function updateTable() {
    $.getJSON("helpers.php", {
        func: "results",
        days: "3",
    }).done(function(rows) {
        // Clear table (only if you have to recreate the whole table)
        // The code below just updates the rows, so this isn't needed.
        //$('#table-results').empty();

        $.each(rows, function() {
            var rowID = this.date; // Use an appropriate ID
            var existingRow = $('#' + rowID);

            // If row does already exist, update it; otherwise create a new one.
            if(existingRow.length > 0) {
                existingRow.find('.teamname').html(this.teamname);
                existingRow.find('.teamscore').html(this.teamscore);
            } else {
                $('#table-results').append([
                    '<tr id="', rowID, '">',
                        '<td><small class="teamname">', this.teamname, '</small></td>',
                        '<td class="teamscore">', this.teamscore, '</td>',
                    '</tr>'
                ].join(''));
            }
        });

        setTimeout(updateTable, 3000);
    });
}

updateTable();
相关问题