How do you write code to refresh data in real time using PHP?

The code for real-time data refreshing in PHP often involves using Ajax or WebSocket technology.

  1. Implement real-time data refreshing using Ajax.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    setInterval(function() {
        $.ajax({
            url: 'refresh.php', // 替换为你的 PHP 文件路径
            success: function(data) {
                // 在此处处理返回的数据
                // 例如更新页面上的某个元素
                $('#dataContainer').html(data);
            }
        });
    }, 1000); // 每隔 1 秒刷新一次
});
</script>
</head>
<body>
<div id="dataContainer"></div>
</body>
</html>

In the code above, an Ajax request is called at regular intervals using setInterval, and the returned data is processed in the success callback function. This allows for refreshing a specific area of the webpage at regular intervals.

  1. Implement real-time data refreshing using WebSocket.
<!DOCTYPE html>
<html>
<head>
<script>
var socket = new WebSocket('ws://localhost:8080'); // 替换为你的 WebSocket 服务器地址

socket.onmessage = function(event) {
    var data = JSON.parse(event.data);
    // 在此处处理接收到的数据
    // 例如更新页面上的某个元素
    document.getElementById('dataContainer').innerHTML = data;
};
</script>
</head>
<body>
<div id="dataContainer"></div>
</body>
</html>

In the code above, a WebSocket object is created and the server address is specified. Data sent from the server is received through the onmessage event. Within the event handling function, the elements on the page can be updated based on the returned data.

Please note that the WebSocket server portion in the above code needs to be implemented separately and requires the use of a server that supports WebSocket, such as the ws module in Node.js.

广告
Closing in 10 seconds
bannerAds