Need help with jQuery
This my script:
<script type="text/javascript">
var auto_refresh = setInterval(
function () {
$('#alert_div').load('/check_messages.php?timestamp=<?php echo TIMESTAMP2;?>').fadeIn("slow");}, 180000);
$("html,body").scrollTop("alert_div",0);
</script>
Actually, everyting works fi开发者_开发百科ne but... As you can see, every 3 minutes script loads check_messages.php file. If user has new messages messages check_messages.php outputs information, otherwise the output is empty:
echo "";
I need that $("html,body").scrollTop("alert_div",0);
exetutes only in case if php script output is not empty.
try that:
<script type="text/javascript">
var auto_refresh = setInterval(
function () {
$('#alert_div').load('/check_messages.php?timestamp=<?php echo TIMESTAMP2;?>', function(response){
if(resonse != '')
$("html,body").scrollTop("alert_div",0);
}).fadeIn("slow");}, 180000);
</script>
The load function takes a function as a parameter, which is called when the request completes with the response text as the first parameter. You can check whether the response was empty in this callback function and scrolling to the top if not then.
Requests such as load
are handled asynchronously, which means that the code that is immediately after it will be run before the call has completed. If you want something to happen after the call has completed then you need to include it in the completion callback. For this reason I do not expect your fadeIn call to work, as I don't think the load function returns the included element. When the load
call returns, your text has not been included in the document.
I've also taken the liberty of moving the code out of your anonymous function into one called check_messages
. In your code you had the scroll to top outside the setInterval
call so it was being executed immediately, rather when the messages were checked.
<script type="text/javascript">
function check_messages() {
$('#alert_div').load('/check_messages.php?timestamp=<?php echo TIMESTAMP2;?>',
function(responseText, textStatus, XMLHttpRequest) {
if(responseText != "") {
$("html,body").scrollTop("alert_div",0);
}
}).fadeIn("slow");
}
var auto_refresh = setInterval(check_messages, 180000);
</script>
You'll need to use something like:
$.get('/check_messages.php?timestamp=<?php echo TIMESTAMP2;?>', function(data) {
if(data) {
$('#alert_div').replace(data);
$("html,body").scrollTop("alert_div",0);
}
});
instead.
I believe you should use the other version of .load as per here - http://api.jquery.com/load/. In the callback, you should check weather there is anything in the response and perform actions based on that condition.
精彩评论