要实现使用jQuery和AJAX每3秒刷新一个div
的内容,可以通过以下完整方案实现:
setInterval()
实现周期性操作<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="refreshable-content">初始内容...</div>
<script>
$(document).ready(function() {
// 定义刷新函数
function refreshDiv() {
$.ajax({
url: 'your-api-endpoint', // 替换为实际API地址
method: 'GET',
success: function(data) {
$('#refreshable-content').html(data);
},
error: function(xhr, status, error) {
console.error("刷新失败: ", error);
}
});
}
// 立即执行一次
refreshDiv();
// 设置3秒间隔定时器
setInterval(refreshDiv, 3000);
});
</script>
</body>
</html>
setInterval(refreshDiv, 3000)
确保每3秒调用一次AJAX请求refreshDiv()
url
:需要替换为实际数据接口地址POST
或其他请求方式data
参数传递查询条件visibilitychange
事件暂停刷新如需更高级的实现(如WebSocket),可根据具体需求调整技术方案。
没有搜到相关的文章