我有一个div,我想在页面加载时刷新,然后每隔60秒自动刷新一次。我现在设置为每60秒刷新一次,但我不知道如何将其与第一页加载相结合。这是整个php页面:
<script>
$(document).ready(function () {
var notify = $("#notify");
notify.hide();
notify.click(function(event) {
// Handle the click on the notify div so the document click doesn't close it
event.stopPropagation();
});
var count = $("#count");
var notifyLink = $("#notify_link");
count.click(showNotification);
notifyLink.click(showNotification);
function showNotification(event) {
$(this).unbind('click', showNotification);
$(this).addClass("selected");
loadData();
notify.show();
$(document).click(hideNotification);
// So the document doesn't immediately handle this same click event
event.stopPropagation();
};
function hideNotification(event) {
$(document).unbind('click', hideNotification);
notify.hide();
notifyLink.removeClass("selected");
count.removeClass("selected");
notifyLink.click(showNotification);
count.click(showNotification);
}
count.load(
"<?php echo $vars['url']; ?>mod/notifications/ajax/livenum.php"
);
$.ajaxSetup({ cache: false });
var refreshId = setInterval(function () {
count.load(
"<?php echo $vars['url']; ?>mod/notifications/ajax/livenum.php"
);
}, 60000);
$.ajaxSetup({ cache: false });
});
function loadData() {
$('#loader').html(
'<?php echo elgg_view('ajax/loader',array('slashes' => true)); ?>'
);
$("#result").load(
"<?php echo $vars['url']; ?>mod/notifications/ajax/data.php",
function () {
$('#loader').empty(); // remove the loading gif
}
);
}
</script>
答案 0 :(得分:2)
在页面加载时执行一次,然后执行setInterval。
function loadCount() {
count.load(
"<?php echo $vars['url']; ?>mod/notifications/ajax/livenum.php"
);
}
$(function () {
var refreshId = setInterval( function () {
loadCount();
}, 60000);
$.ajaxSetup({ cache: false });
}
根据建议进行编辑,使代码更易于维护。
答案 1 :(得分:1)
只需拨打
即可 count.load(
"<?php echo $vars['url']; ?>mod/notifications/ajax/livenum.php"
);
在页面加载。使用jQuery,你可以做这样的事情(把代码放在一个函数中,就像Anthony指出的那样):
$(function() {
function loadCount() {
count.load(
"<?php echo $vars['url']; ?>mod/notifications/ajax/livenum.php"
);
}
// Load on page load (call the function loadCount):
loadCount()
// Set the refresh interval and call the function loadCount every 60 seconds):
var refreshId = setInterval(loadCount, 60000);
$.ajaxSetup({ cache: false });
});
答案 2 :(得分:-1)
您的方法是正确的 - 使用setInterval应该按预期工作。我写了一个快速测试,只使用console.log(),它的工作原理。但我认为你的错误在loadData()中的.load()函数中 - 你没有使用双引号,所以'<?php echo elgg_view('ajax/loader',array('slashes' => true)); ?>'
被解释为三个独立的字符串。你想要的是"<?php echo elgg_view('ajax/loader',array('slashes' => true)); ?>"
(用双引号括起来)。