将服务器端变量传递给客户端JavaScript的最佳方法是什么? [英] What is the best way to pass server side variables to JavaScript on the client side?

查看:60
本文介绍了将服务器端变量传递给客户端JavaScript的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序使用许多配置选项.这些选项需要以用户首选项,站点范围内的首选项等形式反映在客户端上.

当前,我们以JSON的形式将服务器端设置传递给客户端,该JSON存储在特定元素的标记中的自定义属性中(并且不,我们的应用程序当前无需担心W3C验证).然后,我们从custom属性中检索数据,并将其解析为JSON对象,以使用jQuery在脚本中使用.

此方法的一个缺点是从事件处理程序中引用元素的属性.我知道这是不满意的,因为它可以创建循环引用,并随后导致内存泄漏.我更喜欢使用jQuery的data函数,但是您不能在页面渲染时从服务器端调用它.

其他人在这种情况下会做什么?

解决方案

以JSON格式返回服务器数据.您可以通过返回一个JSON标头或简单页面输出和 JSON.parse()来通过AJAX进行此操作.

您可以将JSON数据直接分配给元素的数据.

  $('#elementid').data('serverdata',data); 

更新

在更好地了解了您的情况之后,出于以下三个原因,建议您使用 data-属性.

  1. 您将拥有符合标准的标记.
  2. 最新版的jQu​​ery依赖 .data 函数.
  3. 所做的更改几乎不需要修改您当前的应用程序(将自定义属性从 customAtt ="value" data-customAtt =值"

此处是有关数据属性的更多信息.>

Our application uses a lot of configuration options. Those options need to be reflected on the client side in the form of User preferences, site wide preferences, etc.

Currently, we pass server side settings down to the client side in the form of JSON that is stored in custom attributes in the markup for a specific element (and no, our application currently doesn't worry about W3C validation). We then retrieve the data from the custom attribute, and parse it into a JSON object for use in script using jQuery.

One drawback to this is referencing attributes on elements from within event handlers. I know this is frowned upon, as it can create circular references, and subsequently memory leaks. I would much prefer to use jQuery's data function, but you can't invoke this from the server side at page render time.

What does everyone else do in this type of scenario?

解决方案

Return the server data in JSON format. You could do this through AJAX by returning a JSON header, or simple page outup and JSON.parse().

You can assign the JSON data directly to an element's data.

$('#elementid').data('serverdata', data);

Update

After better understanding your situation I would suggest you use the data- attributes for three reasons.

  1. You will have standards compliant markup.
  2. The recent version of jQuery relies on these for the .data function.
  3. The change will require little modification to your current application (changing the way custom attributes are output from customAtt="value" to data-customAtt="value"

Here is some more information on the data attributes.

这篇关于将服务器端变量传递给客户端JavaScript的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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