没有刷新页面的 php/js 刷新变量

php/js refresh variable without refresh page

本文关键字:刷新 js php 变量      更新时间:2023-09-26

我的php/js代码有问题。

我需要每 1 秒检查一次文件的内容,所以在我要加载页面之前,我将地址.txt内容设置为"localhost",然后我去我的网站,它向我显示 localhost,现在我想将文本文件的内容编辑为"192.168.0.1",所以我想自动将div 文本设置为新内容而无需刷新, 它仍然是本地主机而不是 192.168.0.1

我的实际js:

    $(document).ready(
        function() {
            setInterval(function() {
                var randomnumber = Math.floor(Math.random() * 100);
                $('#show').text("<?php echo file_get_contents("adress.txt");?>");
            }, 1000);
        });

如何在不刷新的情况下将div 文本更新为新的 txtfile 内容?

对不起,英语不好:)

PHP 是一种服务器端语言。仅当加载(或刷新)页面时,才会执行<?php echo file_get_contents("adress.txt");?>。然后,如果你想在不刷新的情况下做任何事情,你需要使用 javascript。如果你想在不刷新的情况下调用一些PHP代码,你可以使用AJAX。如果你只是想获取某个文件的内容,你甚至不需要PHP。

试试这个:

$(document).ready(function()
{
    setInterval(function()
    {
        $.get('address.txt', function(data)
        {
            $('#show').text(data);
        });
    }, 1000);
});