Equating Javascript and PHP Variables

2019-08-30 09:37发布

问题:

<?php 

$a="cat";

$html=<<<HTML
<html>
<script>
   var b ="$a";
   document.write(b);
</script>
</html>
HTML;

echo $html;?>

this code displays cat,is this a valid way of equating javascript variables to php variables,

回答1:

Valid is maybe not the word I would use. Does it work, is a more important question to me. In general, because PHP runs at the server before returning the page to the browser, which then interprets and executes JavaScript, you can definitely write in variables that JS will use. So will this work? sure.

Is there a better way of doing this? Yes, absolutely. In general you don't want blocks of executable JS statements residing in a PHP script. This just muddles things up and makes them very tough to maintain. I would prefer to actually have JS request the value through an AJAX call to a PHP service. If you must use this approach, I would still separate concerns a little better.

EDIT: This works for me:

<html>
<head>
    <title>PHP-JS Writer</title>
</head>
<body>
    <?php
        $a = "cat";
        echo "<script>var b = '$a'</script>";
    ?>      
    <h1>Writing JS variables with PHP</h1>
    <script>
        alert(b);   
    </script>
</body>
</html>


回答2:

If you want to convert PHP variables to Javascript, you can best use json_encode, because it handles all escaping and such for you:

<?php $a = "some value"; ?>

<script>
    var a = <?php echo json_encode($a); ?>;
    console.log(a);
</script>

You can use this for more complex structures as well:

<script>
    var a = <?php echo json_encode(array('property' => 'value')); ?>;

    console.log(a.property);
</script>

Of course, PHP is evaluated server side and JavaScript client side, so there is no way to let JavaScript "talk to PHP" as if it were in the same execution scope, which they aren't by definition. This is a very basic concept of serialization and deserialization to have one platform use the data from another.

You could implement asynchronous requests ("ajax") to retrieve the data from the server, and have the server respond in JSON as well, so the Javascript engine can parse the response contents natively. This has the upside of your client to be able to re-retrieve the data without reloading, but the downside of needing to do (at least) two HTTP requests.