更新PHP变量时自动刷新div [英] Refresh a div automatically when a PHP variable is updated

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

问题描述

我有一个调用变量的div。当该变量发生变化时,用户需要刷新页面以查看新值。该变量是从一个单独的PHP文件中提取的。

I have a div that calls a variable. When that variable changes, users need to refresh the page to see the new value. The variable is pulled from a separate PHP file.

我想知道是否有办法使用ajax自动更新div,而无需用户刷新浏览器,因为它看到PHP变量已更新。

I'm wondering if there's a way to use ajax to automatically update the div without the user refreshing the browser when it sees the PHP variable has been updated.

推荐答案

您可以使用ajax定期检查变量是否发生了变化,如果发生这种情况,您可以更新div。 / p>

You could periodically check if there have been any change to the variable using ajax and if that is the case you could update the div.

var previousValue = null;

function checkForChange() {
    $.ajax({
        url: 'http://example.com/getVariableValue.php',
        ...
        success: function(data) {
            if (data != previousValue) { // Something have changed!
                //Call function to update div
                previousValue = data;
            }
        }
    });
}

setInterval("checkForChange();", 1000);

我没有测试过代码,但它应该是这样的。将从 http://example.com/getVariableValue.php 获取数据,您必须填写一些关于AJAX请求的信息。我假设您知道如何修改您的特定数据格式的代码,无论是XML,JSON还是文本。

I havn't tested the code, but it should be something like that. Will get data from http://example.com/getVariableValue.php, you'll have to fill in some information about the AJAX request. I'm assuming you know how to modify the code for your specific data format, be it XML, JSON or text.

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

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