等同Javascript和PHP变量 [英] Equating Javascript and PHP Variables

查看:78
本文介绍了等同Javascript和PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php 

$a="cat";

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

echo $html;?>

此代码显示cat,这是将javascript变量等同于php变量的有效方式,

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

推荐答案

有效可能不是我会用到的单词。它是否有效,对我来说是一个更重要的问题。一般来说,因为PHP在将页面返回给浏览器之前运行在服务器上,而浏览器然后解释并执行JavaScript,所以您肯定可以编写JS将使用的变量。这项工作将如何?当然。

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.

有没有更好的方法来做到这一点?是的,一点没错。一般来说,您不希望可执行JS语句块驻留在PHP脚本中。这只是混淆了事情,使他们很难维护。我宁愿实际上让JS通过对PHP服务的AJAX调用来请求该值。如果你必须使用这种方法,我仍然会将问题分开一点。

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.

编辑:这适用于我:

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>

这篇关于等同Javascript和PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆