【问题标题】:Ajax refresh div after all data is loaded加载所有数据后Ajax刷新div
【发布时间】:2014-05-16 22:20:30
【问题描述】:
我有一个 ajax 刷新 div 函数,它每 10 秒刷新一个 div。但是,有时它会在从 mysql 获取数据之前加载 div。再次加载 div 后如何让它等待 2 秒?
<script type="text/javascript">
function updateServers(){
$('#content').load('servers.php #content').fadeIn();;
}
setInterval( "updateServers()", 10000 );
</script>
【问题讨论】:
-
听起来你只想在 ajax 调用返回后调用 .fadeIn() 。由于调用是异步的,那么您可能应该使用内置于 .load() 中的完整函数回调,请参阅文档api.jquery.com/load
标签:
javascript
jquery
ajax
【解决方案1】:
可以使用load方法的回调函数:
$( "#result" ).load( "ajax/test.html", function() {
$('#content').fadeIn();
});
【解决方案2】:
我认为你最好在检索到数据后设置一个 setTimeout!
$("#content").load("servers.php #content",
function (responseText, textStatus, XMLHttpRequest) {
if (textStatus == "success") {
setTimeout( "updateServers()", 10000 ); // Will only occur once
}
if (textStatus == "error") {
// oh no!
}
}
【解决方案3】:
试试这个:
<script type="text/javascript">
function updateServers(){
//Put some delay before refresh
setTimeout(function () {
$('#content').load('servers.php #content').fadeIn();
}, 2000);
}
setInterval( "updateServers()", 10000 );
</script>