除非我使用die(),否则javascript不会在PHP循环中执行

时间:2016-10-24 09:59:58

标签: javascript php

我在if语句中使用了这个简单的PHP代码。

<?php
$x = 1;
if($x == "1"){
    echo '<script>alert("hello"); window.open("wwww.google.com","_blank");</script>';
    //die(); works if this is uncommented
}

?>

所以我上面有代码,奇怪的是JS部分只在我在if语句中使用die时执行,我不想这样做,因为页面不仅仅以if语句结束还有一堆其他的东西发生在下面。所以我想知道为什么会这样,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以使用die();直接打印最终的JavaScript,因此将所有JS存储为字符串变量,然后die('<script>.....</script>');,并且每件事都可以正常工作。

<?php
$x = 1;
if($x == "1"){
$script = "<script>
                var hello = 'Hello';
                hello += ' Sir'; ";
$script .= "alert(hello);</script>";
    die($script);
}

?>

现在输出

        <script>
        var hello = 'Hello';
        hello += ' Sir';
        alert(hello);
        </script>

for for循环的示例

<?php
$x = 1;
if($x == "1"){
    $script = "<script>
                var hello = 'Hello';
                hello += ' Sir'; ";
    $script .= "alert(hello);
                </script>";


    $script .= "<script>";
    for($i = 0; $i<5;$i++){
        $script .= "console.log(".$i.");";
    }
    $script .= "</script>";
    die($script);
}

?>

更新:在return内使用function的另一种方式:

<?php
function echoScript(){
$x = 1;
if($x == "1"){
$script = "<script>
                var hello = 'Hello';
                hello += ' Sir'; ";
$script .= "alert(hello);</script>";
    echo $script;
return;
//so all other scripts inside this function not excuted
}
echo "this shouldn't displayed because function has return";
//and all after won't work
//...... 

}//end of function echoScript()


//call function
echoScript();
?>