将 PHP 设置传达给 Javascript 的最佳方式是什么?

发布于 2024-10-08 12:22:19 字数 906 浏览 0 评论 0原文

当您构建一个使用 PHP 在服务器端设置设置的应用程序时,在页面加载时将这些设置传递给 Javascript 的最佳方式是什么?

为什么要在服务器端设置所有设置,而不是部分设置客户端、部分设置服务器端? 因为应用程序肯定是用 PHP 编写的,但 Javascript 部分可能是用纯 Javascript、JS Prototype、jQuery 编写的,... 因此,我们为整个应用程序保留一组独立于 Javascript 层的 PHP 函数。

我自己一直在考虑几个解决方案:

1。通过隐藏表单字段:

<input typ="hidden" name="settings" value="JSON encoded settings" />

缺点:

  • 直接在源代码中查看。
  • 输入hidden是为了提交隐藏数据,而不是获取数据。

2.使用 Ajax

一旦页面加载,就会向服务器发出一个 ajax post 请求来检索设置。

优点:

  • 干净的
  • 客户端只能请求它需要的设置。

缺点:

  • 页面加载较重

3。直接通过源设置文件(XML)

优点:

  • Javascript和PHP代码完全解耦(关于设置)。

缺点:

  • 设置文件加载两次(服务器端+客户端)

4。还有其他吗?

编辑:为 2 号添加了一项优势

When you are building an application where settings are set serverside with PHP, what's the best way to communicate these settings to Javascript on pageload?

Why set all settings serverside and not partly clientside, partly serverside?
Because the app is certainly in PHP, but the Javascript part may be written in plain Javascript, JS Prototype, jQuery, ...
So this way we remain one set of PHP functions for the whole app independent of the Javascript layer.

I have been thinking of a couple of solutions myself:

1. Via a hidden form field:

<input typ="hidden" name="settings" value="JSON encoded settings" />

Disadvantages:

  • Directly viewable in the source code.
  • Input hidden is meant to submit hidden data, not to get data.

2. With Ajax

As soon as the page loads, there is an ajax post request to the server which retrieves the settings.

Advantages:

  • Clean
  • Clientside can request only the settings it needs.

Disadvantages:

  • Heavier page load

3. Directly via the source settings file (XML)

Advantages:

  • Javascript and PHP code are completely decoupled (concerning the settings).

Disadvantages:

  • Settings file is loaded twice (serverside + clientside)

4. Something else?

Edit: added one advantage for number 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半仙 2024-10-15 12:22:19

任何格式(如 yaml、json、xml 等)都可以,因为您可以使用 PHP 读取它并将其转换为每种格式。

也许您的情况最好的解决方案是 json 格式的配置文件。您可以在需要时直接使用 JS 和 PHP 来读取它。

Zend Framework 有一个很好的 JSON 编码/解码组件

Any format like yaml, json, xml, etc. is ok because you can read it with PHP and transform it into each of the formats.

Maybe the best solutions in your case is a json formatted configuration file. You can read that directly with both JS and PHP when needed.

The Zend Framework has a nice JSON encoding/decoding component.

爱本泡沫多脆弱 2024-10-15 12:22:19

php 可以生成 javascript 你知道...

<script type="text/javascript">
    var my_var = '<?php $my_var ?>';
</script>

php can generate javascript you know...

<script type="text/javascript">
    var my_var = '<?php $my_var ?>';
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文