将变量从服务器后端传递到 JavaScript 的正确方法?
我需要将 php 知道的变量传递给我的 javascript 代码,我想知道执行此操作的正确方法是什么。
我已经知道我可以将其添加到页面生成中:
<script type="text/javascript">
var someJSVariable = <?php echo $somePHPVariable ?>
</script>
但我发现这种方法比我想要的更引人注目。 我想知道是否有更好的方法来做到这一点,或者我是否只能将内联 javascript 代码注入到视图脚本中?
I need to pass a variable that php is aware of to my javascript code and I'm wondering what the correct way to do this is.
I already know that I could add this to the page generation:
<script type="text/javascript">
var someJSVariable = <?php echo $somePHPVariable ?>
</script>
But I find this method to be more obtrusive than I'd like. I am wondering if there is a better way to do this, or am I stuck with having to just inject inline javascript code in to the view script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果只有 1 个变量,我认为这是最好的解决方案。 如果您不想将 JS 混合到普通视图中,请创建一个单独的视图,该视图将呈现为 .js 文件,然后在“真实”视图中包含指向该 .js 的链接。 如果你需要性能,那么就需要一些智能接球。
如果有超过 1 个变量,例如 html 文档和服务器之间的数据交换,您可以使用 [AJAX](http://en.wikipedia.org/wiki/Ajax_(programming))。
If it's just 1 variable, I think this is the best solution. If you don't want to mix in JS into your normal view, make a separate view which will be rendered as .js file and then just include a link to that .js in your "real" view. If you need performance, some smart catching would be needed there.
If there's more then 1 variable, for example a data exchange between html document and server you could use [AJAX](http://en.wikipedia.org/wiki/Ajax_(programming)).
我喜欢
json_encode()
这种事情。但是,是的,您被这种内联方法“困住”了。 老实说,你更喜欢这个吗?
不这么认为。 内联方法是 php 的支柱。 随它去吧。
I love
json_encode()
for this kind of thing.But yes, you are "stuck" with this inline approach. Honestly, would you prefer this?
Didn't think so. The inline approach is php's bread and butter. Go with it.
您始终可以向单独的 URL 发出异步请求来获取动态值。 但是,当页面加载时,您会受到轻微的性能损失。 考虑到这一点,我会推荐您概述的内联方法。
您还可以包含另一个“js”文件,它实际上是一个 PHP 页面,它生成一堆 JavaScript 常量,然后您可以在主页中访问这些常量。
You can always make an asynchronous request to a separate URL to get the dynamic value. But, you will take a slight performance penalty there as the page loads. With that in mind, I would recommend the in-line method you outlined.
You could also include another "js" file that's really a PHP page that's generating a bunch of javascript constants that you can then access in your main page.