首页 > 解决方案 > 防止 Ajax 聊天加载到页面顶部

问题描述

我在我的 Web 应用程序中使用 PHP Ajax 解决方案进行聊天。聊天看起来很整洁,但是在聊天室里我遇到了一个大问题。我正在使用 asetInterval来获取新消息,但是当间隔每秒运行一次时,页面最终会跳转到第一条消息。这种情况每秒钟都会发生一次,从而阻止用户看到最新消息。这是我正在运行的脚本:

<?php
    $id = $_GET['id'];
    echo
    "<script>

        function ajax() {
            var req = new XMLHttpRequest();

            req.onreadystatechange = function () {
                if(req.readyState == 4 && req.status==200){
                    document.getElementById('content').innerHTML = req.responseText;
                }
            }
            req.open('GET', 'process.php?id=$id',true);
            req.send();
        }
        setInterval(function () {
            ajax();
        }, 1000);
    </script>
";
    ?>

这是我正在加载内容的 HTML:

<div class="card bg-sohbet border-0 m-0 p-0" style="height: 100vh;">
        <div id="sohbet" class="card border-0 m-0 p-0 position-relative bg-transparent" style="overflow-y: auto; height: 100vh;" onload="ajax();">
            <div id="content"></div>
       </div>
 </div>

我试过使用setTimeout/clearTimeout,event.preventDefault()return false;. 这些解决方案都没有奏效。如果您能提供帮助,将不胜感激。

请查看此视频链接以获取示例:https ://www.hippovideo.io/video/play/gO83luY-81NfIeSeltBW-Q

标签: javascriptphpjqueryhtmlajax

解决方案


推荐阅读