can anybody explain why this is? here my code:
<script>
$(document).ready(function()
{
refresh();
});
function refresh()
{ 开发者_运维百科
$.getJSON('getMessageDetails.php', function (json) {
//alert(json.length);
//$("#subject1").html(json[0].subject);
//$("#unique_code1").html(json[0].unique_code);
$("#msg_id").html(json[0].id);
$("#subject").html(json[0].subject);
$("#unique_code").html(json[0].unique_code);
if (json.length > 0 )
{
//alert(json.length);
window.location.reload();
}
else
{
//do something
}
});
window.setTimeout(refresh,30000);
}
</script>
What I am trying to do is if a new message came in json wont be empty so reload the page and if there are no new messages, keep on checking
What happens now is a new message comes in and the screen just starts flashing like crazy! It must do the reload once and then every 30 seconds check again. Any help please? Thank you.
I think you should do:
$(document).ready(function()
{
var int = setInterval(refresh,30000);
});
function refresh()
{
$.getJSON('getMessageDetails.php', function (json) {
//alert(json.length);
//$("#subject1").html(json[0].subject);
//$("#unique_code1").html(json[0].unique_code);
$("#msg_id").html(json[0].id);
$("#subject").html(json[0].subject);
$("#unique_code").html(json[0].unique_code);
if (json.length > 0 )
{
//alert(json.length);
window.location.reload();
}
else
{
//do something
}
});
}
I think you are looking for setInterval
instead as it sound like you want to call your function every 30 seconds instead of reloading the whole page (that's what window.location.reload
does).
Example:
function sayHello(){
alert('hello once again');
}
setInterval(sayHello,30000);
So what you have to do is wrap your AJAX call in a function and then apply a setInterval
that defines when it gets repeated.
精彩评论