Refresh table data every 5 seconds

2019-07-15 17:59发布

I am in the design stage at the moment and was wondering how I would update a table every 5 seconds.

My table will display read-only data returned from my model.

Normally my view would just have <table></table> HTML and then a foreach loop to write out the data.

However because I want to refresh this whole table every 5 seconds I am unsure how to implement it.

I know there is the javascript setinterval function but I'm also unsure what to do at that point. Would it be something like this?

eg/

function getdata()
{
    $.getJSON("/mycontroller/mymethod"), 

                 function(data) {

                $.each(data, function(i, item) {
                    var row = {  item.ID, item.Date,
                         item.Title
                    };
               $(#table).tableInsertRows(row);
                });

            });
}
    setInterval( "getdata", 5000 );

1条回答
SAY GOODBYE
2楼-- · 2019-07-15 18:53

It might be easiest to have your mymethod action render a view instead of returning JSON. Then you could just set the innerHTML of a div to the ajax response.

Otherwise your approach will work, but you obviously have to delete the existing table rows first:

$('#table').tableRemoveRows({from:0, length:???});

Edit

re-reading your question, it sounds like you're asking more about setInterval than actually creating the table. You need to keep re-registering the callback, so something like this:

function getdata()
{
    $.getJSON("/mycontroller/mymethod"), function(data) {

        $.each(data, function(i, item) {
                var row = {  item.ID, item.Date,
                     item.Title
                };
           $(#table).tableInsertRows(row);
        });

        setInterval( getdata, 5000 );

    });
}
setInterval( getdata, 5000 );
查看更多
登录 后发表回答