javascript - 防止 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
解决方案
推荐阅读
- node.js - 如何从 get 方法中的 cors 禁用选项方法
- python - 使用 Symfit 进行全局拟合:数据集的类型结构
- kotlin - Kotlin-Native cinterop 从 C 更新 Struc 字段
- scala - AnalysisException:在数据架构中发现重复的列:`hour`、`eventTime`
- clickhouse - 将具有动态更改架构的事件数据流式传输到 ClickHouse
- laravel - laravel 无法访问关系属性
- python - Python多处理函数卡在一个带有while循环的函数中
- java - Android 照片上的 EXIF 方向字段为空
- angular - Angular 表单在使用 ng-zorro 初始化时未显示错误
- python - 如何在具有轮廓的 Numpy 2D 数组中找到形状?