use*_*972 24 javascript php ajax jquery
我从一个网站获得了这个代码,我根据自己的需要进行了修改:
<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>
Run Code Online (Sandbox Code Playgroud)
在test.php中:
<?php echo 'test'; ?>
Run Code Online (Sandbox Code Playgroud)
所以我希望在链接div中每隔5秒调用一次test.php.我怎么能这样做?
Yun*_*lam 51
试试吧.
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);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
尝试使用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>
Run Code Online (Sandbox Code Playgroud)
UPDATE
您使用的是旧版本的jquery,因此请包含最新的jquery版本
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
小智 5
尽量不要使用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);
}
});
}
Run Code Online (Sandbox Code Playgroud)