我有一个脚本可以检查我网站成员收到的邮件,但我需要每隔60秒左右运行一次。这是我正在使用的代码:
<script type="text/javascript">
$(document).ready(function()
{
var yourid = <?php echo json_encode($yourid); ?>;
function fetch_messages(){
$.ajax({
url: "php/check-messages.php",
type: "POST",
data: { id : yourid },
dataType: "json",
success: function(data) {
$('#headerInbox').addClass("headerAlert");
}
});
}
$(function(){
fetch_messages();
});
});
</script>
这适用于页面输入并运行#headerInbox addclass但是我需要它每60秒运行一次,然后在找到成功时停止。我怎样才能实现这个目标?
答案 0 :(得分:2)
<script type="text/javascript">
$(document).ready(function()
{
var yourid = <?php echo json_encode($yourid); ?>;
var fetchInterval;
function fetch_messages(){
$.ajax({
url: "php/check-messages.php",
type: "POST",
data: { id : yourid },
dataType: "json",
success: function(data) {
$('#headerInbox').addClass("headerAlert");
clearInterval(fetchInterval);
}
});
}
fetchInterval = setInterval(fetch_messages, 60000);
});
</script>
这应该有效 - 创建一个间隔“fetchInterval”,它会每隔60秒调用一次fetch_messages,然后在成功时清除间隔。
答案 1 :(得分:1)
使用setInterval
和clearInterval
来实现这一目标:
<script type="text/javascript">
function fetch_messages(){
var $interval = setInterval( function () {
var yourid = <?php echo json_encode($yourid); ?>;
$.ajax({
url: "php/check-messages.php",
type: "POST",
data: { id : yourid },
dataType: "json",
success: function(data) {
$('#headerInbox').addClass("headerAlert");
clearInterval($interval);
}
});
}, 60 * 1000);
}
$( function() {
fetch_messages();
});
</script>
答案 2 :(得分:1)
试试这个
<script type="text/javascript">
$(document).ready(function()
{
var yourid = <?php echo json_encode($yourid); ?>;
function fetch_messages(){
$.ajax({
url: "php/check-messages.php",
type: "POST",
data: { id : yourid },
dataType: "json",
success: function(data) {
$('#headerInbox').addClass("headerAlert");
clearInterval(myTimer);
}
});
}
var myTimer = setInterval(function(){fetch_messages()()},6000);
});
</script>