PHP 中包含动态 Javascript
我正在构建一个应用程序(字面意思是在线应用程序),并且我想仅在需要时才动态调用 Js 文件/函数。此外,这是更重要的一点,能够将带有返回值的 php 变量和函数传递到 Js 代码中实际上会让我受益匪浅。这样,传递的变量将发生在服务器端,并且我将受益于仅拥有当时需要的客户端代码。
为此,我正在考虑创建多个简单包含以下内容的 PHP 文件:
<?
//JS CODE FOR PAGE 1 (ETC.)
//HEADER FUNCTIONS
?>
<script type="text/javascript">
//FUNCTIONS, METHODS, ETC WITH THE ABILITY TO INSERT PHP VARIABLES LIKE SO:
var name = <?= $name ?>
</script>
有人反对吗?为什么这不是管理 Js 代码、通过包含和传递数据动态调用它的有效方法?我没有想到什么?
I'm building an application (literally, an online application) and I'd like to dynamically call Js files/functions into play only when they are needed. Additionally, and this is the kicker, it would actually benefit me to be able to pass php variables and functions with return values into the Js code. This way, the variables passed will occur server-side, and I'll have the benefit of only having the client-side code I need at the time.
To this end I'm considering creating multiple PHP files that simple contain the following:
<?
//JS CODE FOR PAGE 1 (ETC.)
//HEADER FUNCTIONS
?>
<script type="text/javascript">
//FUNCTIONS, METHODS, ETC WITH THE ABILITY TO INSERT PHP VARIABLES LIKE SO:
var name = <?= $name ?>
</script>
Does anyone have any objections? Why would this NOT be an efficient way to manage Js code, call it dynamically by including, and passing data? What am I not thinking of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我的应用程序中,如果需要的话,我也只加载 js 文件。我不知道你是否这样做,但我正在使用 MVC 结构。因此,在预调度时,我会检查是否存在与我的控制器同名的 js 文件。这样,只有当控制器/操作确实需要它们时,它们才会被加载。但这样我只包含静态 js 文件,而不包含 PHP 变量的动态文件。我想,到目前为止我还不需要这个;)
但是使 js 文件与控制器或控制器内的操作或两者相关是仅加载 js 文件的一个非常好的方法,这是我真正需要的。
In my applications I am also loading only js-files, if needed. I don't know if you do, but I am using a MVC-structure. So while predispatching I am checking if there is an js-file existing with the same name as my controller for example. This way they get only loaded, if the controller/action really needs it. But this way I am only including static js-files, nothing dynamic with PHP-variables. I guess, I just didn't need that so far ;)
But making your js-files related to a controller or action within the controller or both is a very great way to load only the js-files, which I really need.
也许您可以使用 PHP 的 json_encode 函数来使您的 PHP 对象可用在 JavaScript 中,例如
Maybe you can use the json_encode function of PHP to make your PHP objects usable in JavaScript like
<script type="text/javascript">
var name = <?= json_encode($name) ?>;
</script>