编码:
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 为假?
编码:
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 为假?
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.
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.
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.
您将使用此代码获得结果..
<?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..
因为在 php 完成页面渲染后,您无法分配任何新的 php 变量。如果您确实想做这样的事情,您可能必须使用 AJAX。