jQuery-页面上的特定div自动刷新

问题描述

我想每3秒自动刷新一个特定的div(带有“ autotest”类),并且我使用此脚本来这样做:

<div class="autotest">some variable</div>

setInterval(function() {
  $('.autotest').load(window.location.href + ' .autotest');
},3000);
@H_502_5@

有点用,但刷新后会包含标记,因此看起来像这样:

<div class="autotest">
  <div class="autotest">some variable</div>
  <div class="autotest">some variable</div>
</div>
@H_502_5@

第一次刷新会像上面一样结束。下次刷新时,不会添加更多的div。每次刷新时,它都会更新好变量。

这是怎么了?

解决方法

您需要在请求中添加一个查询参数,例如“ isajax = true”,以告知您的php代码这是ajax调用,并且不需要在输出中包含周围的div。

在您的php文件中,您可以简单地添加一个if子句以根据查询参数发送不同的输出:

if (!empty($_GET['isajax']) && $_GET['isajax'] == 'true') {
    // response without html tag
} else {
    // normal html response
}
,

感谢您对@Alimo的帮助。我无法使其正常工作,但可能是我。我决定将变量放入另一页,然后简单地加载该页。

setInterval(function() {
  $('.autotest').load('autotest.php');
},3000);