在页面加载时向 Ajax 客户端发送初始配置变量的常用方法有哪些?

发布于 2024-12-06 16:01:37 字数 445 浏览 4 评论 0原文

复杂的 Web 应用程序可能具有大量用户和/或上下文特定的元和配置信息。例如,用户首选的结果集大小、时区、一周的开始(周日/周一)等。

在加载时将变量传输到客户端应用程序的可能方法有哪些(隐藏变量?嵌入在某处的 JSON?),每种方法的优点/缺点是什么?

我知道一些将事物组合在一起的方法,但我很好奇是否有人已经确定了可以使用的良好设计模式,或者他们可以分享的最佳实践。

虽然我更喜欢这方面的一般信息,但我的主要堆栈是 jLAMP(jQuery、Apache、MySQL、PHP)

编辑:我已经有执行此操作的应用程序,所以我不寻找快速修复,或建议完全不同的范例(例如,不加载配置)。我正在寻找对每个选项和优缺点的讨论,以便我可以调整我所拥有的内容,或者向新用户提供大量选项以做出良好的设计决策从一开始。谢谢!

A complex web-app can have a large amount of user and/or context specific meta and configuration information. eg, user's preferred result-set size, timezone, beginning of the week (Sun/Mon), etc.

What are the possible ways to transport the variables to the client application as it is loading (hidden variables? JSON embedded somewhere?), and what are the pros/cons of each method?

I know of a few ways to hack things together, but I'm curious if anyone has identified good design patterns to use, or best practices they can share.

Although I'd prefer general info on this, my primary stack is jLAMP (jQuery, Apache, MySQL, PHP)

EDIT: I already have applications that do this, so I'm not looking for a quick fix, or suggestions for an entirely different paradigm (as in, not loading config). I'm looking for a discussion with the options and pros/cons of each, so that I might tune what I have, or a new user would be presented with plenty of options to make a good design decision from the start. Thanks!

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

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

发布评论

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

评论(6

⊕婉儿 2024-12-13 16:01:37

正如其他人指出的那样,如果在加载应用程序期间需要传输大量信息,我不建议使用 AJAX,因为您会增加连接开销。

我选择的方法是使用 PHP 在应用程序的 head 标签上呈现所有配置信息,这样,一旦触发事件(我假设 DOM 完成加载之后),您就可以使用所有信息。

代码示例:

<head>
<script type="text/javascript">
 //Some js code here....
  var myConfigurationName = "<?=$myConfigurationNameFromDatabase;?>";
 //Some more js code here...
</script>
</head>

格式化配置数据的方式完全取决于您,这完全取决于所有数据的相关程度,或者您可能需要在多少个不同的地方/对象/函数中使用它。

您可以根据您的数据创建一些不同的配置对象,或者仅创建一个集中所有这些对象的配置对象。这实际上取决于您迄今为止的应用程序设计。

如果您的 JS 代码有很强的面向对象设计,您可以查看此网站,看看是否有以下任何一个:基本图案符合您的需求。

请随意详细说明您的设计(如果可以的话),以帮助我们了解您的立场以及我们如何为您提供帮助。

快乐编码!

As others have pointed out, if there is a lot of information to transport during the loading of your application I would not recommend using AJAX, since you're putting an overhead on your connection.

My chosen method would be to render all the configuration information on the head tag of your application, using PHP, that way, once your events get triggered (after the DOM has finished loading I would assume), you have all the information at your disposal.

Code example:

<head>
<script type="text/javascript">
 //Some js code here....
  var myConfigurationName = "<?=$myConfigurationNameFromDatabase;?>";
 //Some more js code here...
</script>
</head>

The way you format your configuration data is completely up to you, it all depends on how related all of it is, or in how many different places / objects / functions you might need to use it.

You could create some different configuration objects depending on your data, or only one that concentrates all of them. It really depends on the application design you have so far.

If you have a strong OO design on your JS code, you could check out this site and see if any of the basic patterns match your needs.

Feel free to elaborate a bit more on your design (if you can) to help us understand where you stand and how we can help you.

Happy coding!

放手` 2024-12-13 16:01:37

对我来说它传递的是一个 JSON 数组。它在客户端非常灵活,我不确定您为什么不使用它。在后端,我使用常规 PHP 数组构建它,然后使用 json_encode 将其转换为 JSON,然后再回显到网页。

<script>var myObject = <?=$mySettings?></script>

现在就可以走了。作为奖励,我只需将 json 对象转换为字符串,然后使用帖子中的单个变量将其传递回 PHP,然后将其转换回 PHP 数组以进行操作并包含到数据库中。

For me it's passing in a JSON array. It's so flexible on the client side I'm not sure why you wouldn't use it. On the backend I build it up using a regular PHP array and then just convert it to JSON using json_encode before echoing to the webpage.

<script>var myObject = <?=$mySettings?></script>

and you're good to go. As a bonus I just convert the json object to a string before I pass it back to PHP using a single variable in a post and convert it back to a PHP array for manipulation and inclusion into a database.

热鲨 2024-12-13 16:01:37

到目前为止,我使用 php 文件来存储应用程序的自定义设置。
然后根据需要将它们包含在页面中。
不要忘记将内容类型设置为“text/javascript”

如图所示,我的配置文件将如下所示:

<?php header('Content-type: text/javascript'); ?>

var myApp = {
    // setTimeOut id
    timeoutID : null,

    // Cards clearance delay
    cardsClearanceDelay : 1500,

    // Add other attribute as needed
}

并将它们包含在我使用 CI 构建应用程序的页面中

<html>
    <head>
        <script type="text/javascript" src="web/get_configuration"></script>
    </head>

web/get_configuration 只需调用控制器呈现我的 javascript 配置文件的操作。

So far I use a php file to store custom setting for my application.
Then include them in a page as I need them.
Don't forget to set content type to "text/javascript"

As illustration, my configuration file will look like:

<?php header('Content-type: text/javascript'); ?>

var myApp = {
    // setTimeOut id
    timeoutID : null,

    // Cards clearance delay
    cardsClearanceDelay : 1500,

    // Add other attribute as needed
}

And include them in the page

<html>
    <head>
        <script type="text/javascript" src="web/get_configuration"></script>
    </head>

I build my application using CI, web/get_configuration just calling controller action to render my javascript configuration file.

痴意少年 2024-12-13 16:01:37

您是否尝试过 jQuery taconite 。

http://jquery.malsup.com/taconite/

JSON 是一种很好的数据交换格式。但这并不是解决所有问题的最佳解决方案。

相比之下,Taconite 模型仅要求服务器返回有效的 XHTML。客户端根本不需要编码!

Have you ever tried jQuery taconite .

http://jquery.malsup.com/taconite/

JSON is a great data exchange format. But it's not the best solution for every problem.

In comparison, the Taconite model only requires that the server return valid XHTML. There is no coding required on the client at all!

甜妞爱困 2024-12-13 16:01:37

首先,您需要弄清楚什么对您来说更重要 - 微调服务器首选项、用户端性能、模块化或其他内容。

因此,您可以使用单独的类以某种单独的方式加载每个模块的配置,甚至可以在 JS 中硬编码一些内容。你会获得敏捷性,但整体上会很混乱,但可能主要是工作上的混乱。可能取决于编码团队或模块开发人员的孤立程度。

您可以将不同类型的配置分开,而不是跨模块传播配置:

  1. 一些临时配置可以存储在 localStorage(或类似的,甚至是 cookie)中,并且您可以通过添加可将配置推送到所有打开的选项卡的事件来获益。当然,只有当一个用户只有一台计算机时,这才很好,但您仍然可以允许将此配置保存到您的服务器。
  2. 用户首选项可能会放入一个序列化对象中(JSON 相当轻)并通过 AJAX 调用发送。您可以在用户更改这些设置后在 PHP 端缓存这些设置并简单地序列化键值对。
  3. 站点范围的配置可能应该分开,因为它很少改变并且可以存储在 JS 文件中。您想在页面加载后加载它吗?很好 - 您可以使用 AJAX 来做到这一点,然后运行 ​​eval。你会得到什么?您还可以静态加载相同的 JS 文件,它会被浏览器缓存,不会每次都加载,并且根本不会被 PHP 解释器触及。

您可以将所有这些混合在一起,因为这在我见过的大多数大型网站中都经常发生。

至于格式,我更喜欢 JSON。它非常轻(特别是与 XML 相比),您可以很好地对其进行 GZIP,使其变得更加轻。 JSON 还可以轻松地随着时间的推移进行扩展(您可以添加和删除选项而不会出现致命故障)并且几乎是 JS 原生的。

至于如何生成JSON...好吧CACHE IT。除了一些特定的偏好之外,大多数配置选项不会经常更改(不像被读取的那么频繁)。

另请注意,配置可以通过多种方式理解 - 在 MediaWiki/Wikipedia 中,您可以添加自己的 JavaScript。

此外,如果您希望用户创建一些额外的脚本,您可能想要表达更多的选项。

First you need to figure out what is more important for you - fine tuning server preference, user side performance, modularity, or something else.

So you could load configuration for each module in some separate way with a separate class or even hardcode some stuff in JS. You would gain agility but it would be an overall mess, but it might be a mostly working mess. Probably depends on how isolated the coding teams or developers of modules are.

Instead of spreading configuration across modules you could separate different kinds of configuration:

  1. Some temporary configuration can be stored in localStorage (or similar, even cookies) and you will gain from adding events that can push the configuration to all open tabs. Of course this would be great only when one user has only one computer, but you could still allow to save this configuration to your server.
  2. User preferences might be put in one serialized object (JSON is pretty light) and sent with AJAX calls. You could cache this settings on PHP side after user would change them and simply serialize key-value pairs.
  3. Site-wide configuration should probably be made separate as it would rarely changed and could be stored in a JS file. You want to load it after page load? Fine - you can do that to with AJAX and then run eval. What would you gain? You could also load the same JS file statically and it would be cached by the browser and not loaded every time and wouldn't be touched by PHP interpreter at all.

And you could mix all this as it mostly happens in most cases of big websites I've seen.

As for the format I would prefer JSON. It's pretty light (especially when comparing to XML) and you can GZIP it nicely to make it even lighter. JSON is also easily extend-able over time (you can add and remove options without fatal failures) and is almost JS native.

As to how generate JSON... Well CACHE IT. Beside some specific things preferences most of the configuration options won't change too often (not as often as being read).

Also note that configuration may be understood in many ways - in MediaWiki/Wikipedia you can add your own JavaScript.

Also you may want to express more options then it is needed if you want your users to create some extra scripts.

緦唸λ蓇 2024-12-13 16:01:37

简单的持久用户选择的选项可能最好由 cookie 设置。
一切更复杂的事情都可以通过 json 值更好地处理。

显然,您可以将自定义 javascript 代码放入标头中以设置 js 变量,但这需要您动态渲染代码,这(恕我直言)丑陋且容易出错。
另一方面,您可以呈现包含所有自定义数据的自定义元标记,并且
稍后用javascript读出它。

我过去简单而优雅的解决方案是在脚本标签中渲染 json
在标题中

<script id="initparams" type="application/json"> 
    [ output of json.dumps({a: "AAA", ....}) ]  
</script>

,然后在 jQuery 文档就绪处理程序中(可以从外部文件加载):

var initparams = $.parseJSON($('#initparams').html());

由于我在两侧使用 json 转储和解析,所以没有机会进行错误转义或
注入攻击。

当我只需要一些不保证的本地参数时,我在

中为属于 jstree 或数据表的选项做了相同的嵌入 json 参数
AJAX 调用。你可以通过 CSS 隐藏 div.options,或者在解析它时将其从 dom 中删除:

var tableoptions = $.parseJSON($('table.mydata > div.options').remove().html());

Simple persistent user selected options are probably best set by cookies.
Everything more complex is better handled by json values.

Obviously you could put custom javascript code into your header to set js variables, but this requires you to render code dynamically, which is (IMHO) ugly and error prone.
On the other hand you can render custom meta tags holding all your custom data, and
read it out by javascript later.

My simple and elegant solution in the past was to just render json in a script tag
in the header

<script id="initparams" type="application/json"> 
    [ output of json.dumps({a: "AAA", ....}) ]  
</script>

And later in a jQuery document ready handler (which may be loaded from an external file):

var initparams = $.parseJSON($('#initparams').html());

Since I use json dump and parse on both sides no chance for wrong escaping or an
injection attack.

I've done the same embedding json params in <div class="options"> for options belonging to a jstree or data table, when I needed just a few local parameters not warranting
an AJAX call. You can either hide the div.options by CSS, or remove it from the dom when parsing it:

var tableoptions = $.parseJSON($('table.mydata > div.options').remove().html());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文