为什么我的内容不加载时使用setInterval自动更新页面?



我有下面的代码,它可以完美地自动更新页面。但是,在初始页面加载期间,获取的内容出现在页面上需要40秒。如何使内容在初始加载期间立即出现,然后在40秒后更新?

$(document).ready(function(){
jQuery(window).on("load", function(){
refreshInterval = setInterval(function(){
$('#box').load('handle.php');
},40000);
});
});

解决方案

$(document).ready(function(){
jQuery(window).on("load", function(){
$('#box').load('handle.php');

refreshInterval = setInterval(function(){
$('#box').load('handle.php');
},40000);

});
})

这是您需要的确切代码。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Stack overflow answer</h1>
<div id="box"></div>
<script>
$(document).ready(function() {
const userAlreadyVisited = localStorage.getItem('visited');
// After the first load it will load the content from handle.php after 2 second every time
if (userAlreadyVisited) {
jQuery(window).on("load", function() {
setTimeout(() => {
$('#box').load('handle.php');
}, 5000);
});
} else {
// The content of handle.php will be loaded immediately after the page load
localStorage.setItem('visited', true);
jQuery(window).on("load", function() {
$('#box').load('handle.php');
});
}

})
</script>
</body>
</html>

下面是handle.php文件的内容

<?php
echo '<h3>Data from handle.php</h3>';

最新更新