每5秒刷新一次使用jQuery/Ajax的表

Ben*_*old 21 php ajax jquery

所以我有一个表从数据库中提取信息,我想知道如何在不重新加载整个页面的情况下刷新信息.

Dut*_*432 37

您需要一个getTable.php显示您的表格的页面,而不是其他内容:没有页眉,页脚等.

PHP(getTable.php) - 这可以是任何服务器端代码(asp,html等).

<?php
    echo '<table><tr><td>TEST</td></tr></table>';
?>
Run Code Online (Sandbox Code Playgroud)

然后,在您的JS中,您可以使用以下load()方法轻松刷新表:

HTML

<div id="tableHolder"></div>
Run Code Online (Sandbox Code Playgroud)

JS

<script type="text/javascript">
    $(document).ready(function(){
      refreshTable();
    });

    function refreshTable(){
        $('#tableHolder').load('getTable.php', function(){
           setTimeout(refreshTable, 5000);
        });
    }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 好的回复.为了帮助澄清,1000毫秒= 1秒.所以:setTimeout(refreshTable,5000); - 每5秒刷新一次表. (4认同)
  • 值得一提(对于像我这样的新手)你需要将jQuery导入<HEAD>中的html文件,例如`<script src ="http://code.jquery.com/jquery-2.1.3.min.js" > </ script>`在这一个上浪费了10分钟! (4认同)

Jef*_*ert 9

使用ajax,以下示例在jQuery中:

$(function() {
    var prevAjaxReturned = true;
    var xhr = null;

    setInterval(function() {
        if( prevAjaxReturned ) {
            prevAjaxReturned = false;
        } else if( xhr ) {
            xhr.abort( );
        }

        xhr = $.ajax({
            type: "GET",
            data: "v1="+v1+"&v2="+v2,
            url: "location/of/server/script.php",
            success: function(html) {
                 // html is a string of all output of the server script.
                $("#element").html(html);
                prevAjaxReturned = true;
           }

        });

    }, 5000);
});
Run Code Online (Sandbox Code Playgroud)

success函数假定您的服务器脚本在id为'element'的元素中输出要替换的html.

  • 该解决方案的"问题"是,一旦加载完成,它就不会启动计时器.换句话说,如果您的请求返回时间超过5秒,则会有重叠的ajax请求.我建议在发起新呼叫之前使用.abort(). (2认同)

Eti*_*uis 6

您应该有一个页面返回信息并使用Ajax/jQuery提取数据.

<div class="result"></div>

setInterval(function() {

    $.get('table.php', function(data) {
      $('#result').html(data);
    });

}, 5000);
Run Code Online (Sandbox Code Playgroud)


小智 2

这是另一个供您使用的选项。该解决方案使用IIFE,它优于 setInterval。您可以通过上面的链接阅读有关 IIFE 的更多信息。

JavaScript:

var $results = $('#results'),
    loadInterval = 5000;
(function loader() {
    $.get('script.php', function(html){
            $results.hide(200, function() {
                $results.empty();
                $results.html(html);
                $results.show(200, function() {
                    setTimeout(loader, loadInterval);
                });
            });
    });
})();
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="results"></div>
Run Code Online (Sandbox Code Playgroud)