问题
I have tried many ways to have the page title automatically update every 3 seconds so the title can display how many unread messages they have.
Here is what I have tried:
setInterval(function() {
document.title = "<?php echo $inboxcc; ?>";
}, 3000);
and
$(function() {
setInterval(function() {
$(this).attr("title", "<?php echo $inboxcc; ?>");
}, 3000);
});
But none of them work.
回答1:
This approach won't work. Your PHP statement will execute once on the server-side, so no matter what you do in JavaScript, the title won't change more than once.
You need an AJAX-based approach, which will set the document.title
property on success:
$.ajax({
url: 'new_page_title.php',
data: {name: 'username', password: 'userpass'},
success: function(data) { document.title = data;},
dataType: 'text'
});
Now: while you certainly can tuck this code into a setInterval
call, I would suggest that checking it every 3 seconds might get to be a bit hard on your server, and not necessary. Every 15 - 60 seconds would be gentler.
setInterval(function() {
$.ajax({
...
});
}, 30000); // milliseconds
回答2:
You need to refresh the data from the server each time you want fresh data, since the PHP block is only executed once per page view (on the server). Make a PHP page like this:
<?php
// data.php
// Grab the user from the session and calculate the 'unread messages' value
$user['inboxcc'] = the_unread_messages_value;
echo json_encode($user);
?>
Then pull the number dynamically like this:
var updater = function() {
$.getJSON('data.php',function(jsonuser){
document.title = jsonuser.inboxcc;
setTimeout(updater,3000);
});
};
setTimeout(updater,3000);
Note that I use setTimeout
instead of setInterval
, since you can't be sure every request will return in 3 seconds. Using setTimeout
is better in general.
回答3:
To complement @mblase75's answer (which is correct), here's a further explanation of the common misconception that you have fallen into.
PHP is a server-side preprocessor which outputs the HTML and Javascript that gets sent to your browser, then has nothing more to do with anything.
So, your PHP:
<?php $inboxcc = 'Title'; ?>
<script type="text/javascript">
setInterval(function() {
document.title = "<?php echo $inboxcc; ?>";
}, 3000);
</script>
Yields the output:
<script type="text/javascript">
setInterval(function() {
document.title = "Title";
}, 3000);
</script>
This is what your browser sees. And that's it.
回答4:
PHP block inside JavaScript can't update information for himself. You need to update title using AJAX, hidden iframe or other way. At this point your code changing <title>
element to the same value.
回答5:
Your php code can't be interpreted in the javascript, so hide the value in a hidden input :
<input type="hidden" id="inboxcc" value="<?php echo $inboxcc; ?>">
now you can call the value in javascript:
setInterval(function() {
document.title = document.getElementById('inboxcc').value;
}, 3000);
来源:https://stackoverflow.com/questions/7445031/auto-refresh-document-title