-4

编码:

if( 4 > 1 ) {
    alert('ok');
    <?php $mode = true;?>
} else {
    alert('not-ok');
    <?php $mode = false;?>      
}
var_dump($mode);

这会发出警报,但var_damp()显示bool(false)

为什么 var_dump 显示 $mode 为假?

4

5 回答 5

3

You're confusing server-side code with client-side code. The PHP doesn't continue to be interpreted in the browser. By the time anything gets to the browser (which interprets the JavaScript code), the PHP is processed and done.

So essentially what you're doing in PHP is this:

$mode = true;
$mode = false;
var_dump($mode);

Which, naturally, will show false. Then, after that's done executing, you're rendering this to the browser:

if(4>1){
    alert('ok');
} else {
    alert('not-ok');
}

Which, naturally, will alert('ok').

You can essentially think of the server-side code and the client-side code as two entirely different application contexts. Indeed, they kind of are. The server-side application is just returning a page, it doesn't care what's on the page or what happens to the page. The client-side application is what gets rendered to the browser and any code therein (JavaScript, in this case). It doesn't care how it was generated by the server or even what server-side language was used (PHP, ASP, Java, etc.), it just does its thing in the browser.

于 2013-03-01T13:07:19.127 回答
1

PHP code is executed on server before page is sent to the browser. At this point, both code chunks: $mode = true; and $mode = false; will be executed, and final value of $mode will be false, so var_dump($mode) will print bool|(false). The page sent to browser will contain the following code:

if(4>1){

        alert('ok');


    } else {
        alert('not-ok');

    }

Your PHP chunks didn't print anything, so they will just turn to nothing. Browser will execute this code and show window with ok in it.

于 2013-03-01T13:08:00.410 回答
0

PHP - Server side - browser does not get a look in nor does Javascript.

So the code given would be delivered to the browser after the PHP has been processed.

于 2013-03-01T13:07:08.557 回答
0

您将使用此代码获得结果..

<?php

echo "<script type='text/javascript'>";

if(4>1){

    echo "alert('ok')";
    $mode = true; 

}

else {
    echo "alert('ok')";
    $mode = false; 
}

echo "</script>";

var_dump ($mode);

?>

您可以在 php 脚本中编写 javascript..

于 2013-03-01T13:26:01.020 回答
0

因为在 php 完成页面渲染后,您无法分配任何新的 php 变量。如果您确实想做这样的事情,您可能必须使用 AJAX。

于 2013-03-01T13:08:59.363 回答