JQuery/Ajax html 仅加载一次

我正在尝试制作一个几乎实时显示两个数据库中的数据的页面。我遇到的问题是 JQuery Ajax 调用仅更改 html 一次


HTML 代码:

    <div class="database">

    <h1>Trying to connect...</h1>

    <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>

    <script type="text/javascript">

        $(".database").each(function update()

        {

            var self = this;

            var i = 0;

            $.ajax(

                {

                    url: "/show",

                    method: 'GET',

                    cache: false,

                    success: function (data) {

                        $(self).html(data);

                        console.log(data);

                    }

                }

            )

           setTimeout(update, 10000);

        });

        update();

    </script>

</div>

在 /show 上运行的 PHP 代码


    try

    {

        $SosAlerts = DB::connection('MSSQLSERVER01')->select('select TOP(10) * from SosAlert ORDER BY date_time DESC');

        echo "<h3>MSSQLSERVER01</h3>

              <table>

        <tr>

                <th>SosAlertID</th>

                <th>XCoordinate</th>

                <th>YCoordinate</th>

                <th>Date And Time</th>

              </tr>";

        foreach ($SosAlerts as $sosAlert) {

            echo "<tr>

                <td> " . $sosAlert->SosAlertID . "</td>

                <td>" . $sosAlert->XCoordinate . "</td>

                <td>" . $sosAlert->ZCoordinate . "</td>

                <td>" . $sosAlert->date_time . "</td>

            </tr>";

        }


问题是,第一次调用时只$(self).html(data)更新一次 html 内容,之后就不再改变了。显示每 10 秒进行一次 ajax 调用,并且在更新数据库时正确更改数据。即我运行 HTML 页面,它显示尝试连接...,之后它更改为显示 10 行的表,并且控制台日志中显示相同的内容,在接下来的 10 秒内我在数据库中插入新行,重复调用,控制台日志转储数据时显示新行,但 html 未更改<div class="database">console.log(data)


慕田峪4524236
浏览 63回答 1
1回答

慕村225694

我怀疑对的引用self在函数调用中丢失了。第一个this引用迭代中的元素.each(),但我打赌该迭代之外的后续调用this引用函数本身。这种让函数调用本身的方法非常尴尬。相反,将操作放入其自己的函数中,然后将该函数设置为一个时间间隔:function update() {&nbsp; &nbsp; $(".database").each(function () {&nbsp; &nbsp; &nbsp; &nbsp; var self = this;&nbsp; &nbsp; &nbsp; &nbsp; var i = 0;&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "/show",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method: 'GET',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(self).html(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });}setInterval(update, 10000);这样,update每 10 秒的每次调用都会调用一次新的调用,每次调用.each()都会依次设置为目标元素。self
打开App,查看更多内容
随时随地看视频慕课网APP