仅当变量更改时,Ajax刷新Div [英] Ajax Refresh Div Only If Variable Changed

查看:49
本文介绍了仅当变量更改时,Ajax刷新Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,可以从另一个页面重新加载数据.代码如下:

I have a div that reloads data from another page. The code looks like this:

var auto_refresh = setInterval(
  function() {
    $('#mydiv').load('load.php');
  }, 1000); // refresh every 1000 milliseconds

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.js"></script>
<div id="mydiv">
  <?php echo 'loading...';?>
</div>

这非常适合刷新我的数据.但是,我真的不希望它每隔1000毫秒刷新一次div,而是希望它检查是否有任何更改,如果有更改,则刷新div.

This works wonderfully to refresh my data. However, I don't really want it to refresh the div every 1000 milliseconds, I want it to check to see if anything has changed, and if so then refresh the div.

例如:

$current_vericode = 'kdsjfkdfj';

$sql = "SELECT\n".
"   vericode\n".
"FROM\n".
"   users\n".
"WHERE\n".
"   users.id = 3";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $new_vericode = $row["vericode"];
        }
    }

if ($current_vericode == $new_vericode)
{
    //don't refresh the div
} else {
    //refresh it and...
    //$current_vericode = $new_vericode
}

这样,所有发生的事情就是检查mysql以查看指定的字段是否已更改.如果没有,那么它什么也不会做.如果有,它将刷新div并更新代码.

This way all that is happening is that it checks mysql to see if the specified field has changed. If it hasn't then it doesn't do anything. If it has then it will refresh the div and update the code.

我知道效果将与不断更新相同,但是我真的想添加一些表单和东西,直到mysql字段更改后,我才能使用它进行更新.

I understand that the effect will be the same as constantly updating, but I really want to add forms and stuff which I could do with it not updating until the mysql field has changed.

因此,每隔1000毫秒,请检查mysql并将其与当前值进行比较.如果它们相同,则结束/退出.如果它们已更改,则刷新并将新值保存为当前值.

So every 1000 milliseconds, check mysql and compare it to current value. If they are the same then end / exit. If they have changed then refresh and save new value as current.

有什么想法吗?

推荐答案

您可以通过两种方式执行此操作:

You can do this in two ways:

第一个调用会检查是否是使用时间戳或最新版本的版本计数器重新加载的时间.

The first call checks whether it's time to reload using a timestamp or version counter with the last good version.

var auto_refresh = setInterval(
  function() {
    $.post('check-load.php').done(function(reply) {
        if (reply.timestamp < $('#mydiv').attr('timestamp')) {
            return;
        }
        $('#mydiv').load('load.php').attr({ timestamp: reply.timestamp });
    });
  }, 1000); // 

2.一个电话

此处在每次调用时都会生成HTML,但只有在需要时才真正加载.不过,每次都会下载.

2. One call

Here the HTML is generated at each call, but only really loaded if needed. It will be downloaded every time though.

  function() {
    $.post('check-load.php').done(function(reply) {
        if (reply.timestamp < $('#mydiv').attr('timestamp')) {
            return;
        }
        $('#mydiv').html(reply.html).attr({ timestamp: reply.timestamp });
    });
  }, 1000); // 

在第二种情况下,您发送的JSON也包含所生成页面的HTML.

In the second case you send a JSON containing also the HTML of the generated page.

如果加载检查很容易且HTML生成速度很慢,则应采用第一种方法.如果流量有问题,则第一种方法会更好.

If the load check is easy and the HTML generation slow, then you should go with the first method. If the traffic's a problem, the first method is better.

//检查加载(带有HTML)

// check-load (with HTML)

以前的代码使MySQL生成一个时间戳,并在时间戳更改时重新加载DIV.下面的代码更接近您的代码:

The previous code has MySQL generate a timestamp and reloads the DIV when the timestamp changes. The code below is closer to yours:

$current_vericode = 'kdsjfkdfj';

$sql = 'SELECT vericode FROM users WHERE users.id = :id';

$rs  = $conn->prepare($sql);
$rs->execute([ ':id' => 3 ]); // or Array(':id' => 3) with older PHPs

...

if ($current_vericode == $new_vericode) {
    $reply = [ 'refresh' => 'no' ];
} else {
    $reply = [ 'refresh' => 'yes', 'html' => '<p>HELLO WORLD</p>' ];
}

Header('Content-Type: application/json;charset=utf-8');
die(json_encode($reply));

但是现在jQuery代码必须稍作更改才能读取.refresh:

But now the jQuery code has to change slightly to read .refresh:

    $.post('check-load.php').done(function(reply) {
        if (reply.reload === 'yes') {
            $('#mydiv').html(reply.html);
        }
    });

史蒂夫的建议

上面,我们将整个套件和kaboodle发送到DIV中进行加载.这是浪费带宽,并且会迫使客户端始终加载相同的HTML,除非您发送一些代码或分析User-Agent来区分客户端.

Steve's suggestion

Above, we send the whole kit and kaboodle to load in the DIV. It's a waste of bandwidth, and it forces the client to always load the same HTML unless you send some code or analyze the User-Agent to tell clients apart.

该DIV中将显示什么?您可以使用把手来填充模板.假设这只是时间,日期和新的验证码:

What is to be displayed in that DIV? You could use Handlebars to populate a template. Say it's just time, date and the new vericode:

if ($current_vericode == $new_vericode) {
    $reply = [ 'refresh' => 'no' ];
} else {
    $reply = [ 'refresh' => 'yes', 'time' => date('H:i:s'), 'auth' => $vericode ];
}

和jQuery中(即使有些DIV有点过分,把手也会更好):

and in jQuery (Handlebars would be lots better, even if it's overkill for a little DIV):

$('#mydiv').empty().append(
    $('<p>').text(reply.time)
).append(
    $('<p>').text('New authcode: ' + reply.vericode)
);

这篇关于仅当变量更改时,Ajax刷新Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆