PHP表达式中的PHP输出

Please consider the following scenario with a simple HTML document and a JavaScript loaded in it:

<!-- doc.html -->
<!doctype html>
<html lang="en">
    <head>        
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
</html>

// script.js
window.onload = function()
{
    var d = new Date();
    d.setHours(<?php echo(date("H")); ?>);
}

It's really Quite simple, isn't it? However, while this coode works perfectly for getting the current hour (which will be returned as an INT), it doesn't if I try to receive a more complex date/time format like the one below:

var serverTime = <?php echo date("Y-m-d H:i:s"); ?>;

This should encode to 1900-01-01 00:00:00. So, cause this is not a legal expression I want to encapsulate the result with quotes:

var serverTime = "<?php echo date("Y-m-d H:i:s"); ?>";

At a first glance this should work. Unfortunately, it doesn't. serverTime contains just an empty string.

What am I doing wrong?

Maybe your Timezone isnt correctly setup

try

<?
    date_default_timezone_set('America/Los_Angeles');
?>

or similar - full list can be found here

http://de3.php.net/manual/en/timezones.php

Try using single quotes:

var serverTime = '<?php echo date("Y-m-d H:i:s"); ?>';

There is no reason why var serverTime = "<?php echo date("Y-m-d H:i:s"); ?>"; shouldn't return something like:

var serverTime = "2011-05-12 05:12:56";

Check to make sure that echo date("Y-m-d H:i:s"); is working correctly.

Other than that, the code should work fine.

See here: http://codepad.org/3CNx1ch9
Output: http://codepad.org/3CNx1ch9#output

Because you are using double quotes in your JavaScript you need to use single quotes in your php.

var serverTime = "<?php echo date('Y-m-d H:i:s'); ?>";

The javascript won't execute your php code. Think of it like this: When the page is rendered php "replaces your php code" with the output of the php code.

So basically this

var serverTime = '<?php echo date("Y-m-d H:i:s"); ?>';

Should be rendered as

var serverTime = '2011-11-28 xx:xx:xx';

I think you are wrong in the way of you insert your parameters. Acording to this I think you should do this:

// script.js
window.onload = function()
{
    var d = new Date('<?php echo(date("F d, Y H:i:s")); ?>');
    d.setHours(<?php echo(date("H")); ?>, <?php echo(date("i")); ?>, <?php echo(date("s")); ?>);    
}

The statment var d = new Date('<?php echo(date("F d, Y H:i:s")); ?>'); is to follow the example of this link.

Because I can't see why php will fail to send the result of the date() function.