AJAX jQuery 每 5 秒刷新一次 div

IT技术 javascript php jquery ajax
2021-02-23 00:16:13

我从一个网站上得到了这个代码,我已经根据我的需要修改了这个代码:

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>

<div id="links">

</div>

<script language="javascript" type="text/javascript">
var timeout = setTimeout(reloadChat, 5000);

function reloadChat () {
$('#links').load('test.php #links',function () {
        $(this).unwrap();
        timeout = setTimeout(reloadChat, 5000);
});
}
</script>

在 test.php 中:

<?php echo 'test'; ?>

所以我希望在链接 div 中每 5 秒调用一次 test.php。我怎样才能正确地做到这一点?

5个回答

试试这个。

function loadlink(){
    $('#links').load('test.php',function () {
         $(this).unwrap();
    });
}

loadlink(); // This will run on page load
setInterval(function(){
    loadlink() // this will run after every 5 seconds
}, 5000);

希望这可以帮助。

用 $(this).unwrap(); 更新了我的答案;在这里你不需要 timeout = setTimeout(reloadChat, 5000);
2021-04-21 00:16:13
它不起作用,ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js是正确的库吗?
2021-04-21 00:16:13
太好了,现在完美了 :) 谢谢
2021-04-23 00:16:13
@rupesh 你能告诉一些其他的方法来从服务器获取新数据而不向服务器发送请求吗?如果要求每5秒刷新一次。谢谢!
2021-04-29 00:16:13
哦,等等,它正在工作,谢谢:) 但是“测试”在页面加载后 5 秒出现,是否可以立即加载然后每 5 秒刷新一次?
2021-05-13 00:16:13

尝试使用setInterval并包含jquery library并尝试删除unwrap()

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

var timeout = setInterval(reloadChat, 5000);    
function reloadChat () {

     $('#links').load('test.php');
}
</script>

更新

您使用的是 jquery 旧版本,因此请包含最新的 jquery 版本

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

尽量不要使用setInterval
您可以在超时成功响应后重新发送请求到服务器。
jQuery:

sendRequest(); //call function

function sendRequest(){
    $.ajax({
        url: "test.php",
        success: 
        function(result){
            $('#links').text(result); //insert text of test.php into your div
            setTimeout(function(){
                sendRequest(); //this will send request again and again;
            }, 5000);
        }
    });
}
这个答案导致了另一个答案stackoverflow.com/a/5052661/3842368,它建议将其从“成功”移至“完成”。赞成。
2021-04-26 00:16:13
你能解释一下为什么不设置间隔吗?
2021-05-12 00:16:13

你可以用这个。

<div id="test"></div>

你的java脚本代码应该是这样的。

setInterval(function(){
      $('#test').load('test.php');
 },5000);
<script type="text/javascript">
$(document).ready(function(){
  refreshTable();
});

function refreshTable(){
    $('#tableHolder').load('getTable.php', function(){
       setTimeout(refreshTable, 5000);
    });
}
</script>