将系统值传递给 JavaScript 的最佳方式

发布于 2024-09-27 15:11:53 字数 739 浏览 1 评论 0 原文

将对象和类别 ID 或其他不应呈现给用户的系统变量从服务器传递到浏览器的最有效方法是什么?

假设我有一个项目列表,我可以通过 javascript 对每个项目执行某些操作,例如显示工具提示 html 或通过 ajax 添加到收藏夹,或显示在地图上。工具提示 html、数据库 ID 或地理位置最好保存在哪里?

我能想到的一些选项是:

  • 每个项目的 标签内的一些字典、
  • 微格式、
  • 内联 xml、
  • rel 属性、
  • css 类名称具有特定信息,例如 class="lat-12345 uid-45678"
  • 一个 带有 html id 字典与系统映射字典模板中的值,
  • 从数据库生成的 javascript,并通过 包含在 html id 字典中,映射字典与系统值模板,
  • 当我需要更多信息而不仅仅是 id 时,ajax 请求所有情况,
  • 在 html 标签内带有参数的事件处理程序,例如 onmouseover="tooltip(this, 123, 'Hello world!')"

PS 我更喜欢不引人注目的解决方案,而且加载/执行时间也很重要。

What is the most effective way to pass object and category ids or other system variables which shouldn't be presented to the user, from server to the browser?

Let's say I have a list of items where I can do something with each of them by javascript, for example show tooltip html or add to favorites by ajax, or display on a map. Where is it best to save that tooltip html, or database id, or geoposition?

Some options I can think of are:

  • some dictionary within <script></script> tag for each item,
  • microformats,
  • inline xml,
  • rel attributes,
  • css class names with specific information, e.g. class="lat-12345 uid-45678",
  • one <script></script> with a dictionary of html ids mapping dictionaries with system values in the template,
  • javascript generated from the database and included via <script src="..."></script> with a dictionary of html ids mapping dictionaries with system values in the template,
  • ajax requests for all cases when I need more information than just id,
  • event handlers with parameters within html tags, e.g. onmouseover="tooltip(this, 123, 'Hello world!')".

P.S. I prefer unobtrusive solutions and also the loading/execution time is important.

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

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

发布评论

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

评论(5

怪我入戏太深 2024-10-04 15:11:53

也许我错过了一些东西......为什么不只是 JSON?

如何“发送”它(无论是在初始页面加载为“javascript”还是通过 AJAX 或其他方式)实际上只是一个微不足道的细节,主要取决于数据何时可用。 (JSON 是合法 JavaScript 语法的子集。)

那么这只是正确转换的问题。当然,通过将其推送到 JSON/JS,您可能会导致某些非 JS 客户端不可互操作(如果您考虑到这一点)。如果情况确实如此,为什么不直接使用您放在顶部的任意数量的技术来执行服务器端转换呢?

您还可以在 HTML 中使用任意属性(HTML5 规范可能包括正式合法化的“data-*”)——虽然技术上不“正确”,但所有主要 Web 浏览器都将接受可通过 DOM API 访问的未知属性。

Perhaps I am missing something... why not just JSON?

How you "send" it (either in the initial page load as "javascript" or via AJAX or whatnot) is really just a trivial detail determined mostly by when the data is available. (JSON is a subset of legal JavaScript syntax.)

Then it's just a matter of the correct transformation. Of course, by pushing this to JSON/JS, you may render some non-JS clients non-interoperable, if that's a consideration for you. If such is indeed the case, why not just perform the transformation server-side using well, any number of the techniques you put at top?

You can also use arbitrary attributes in HTML (the HTML5 spec may include "data-*" which is formally legalized) -- while not technically "correct", all major web-browsers will accept unknown attributes which can be accessed through the DOM API.

合久必婚 2024-10-04 15:11:53

我更喜欢一个 AJAX 调用来获取您一开始就需要的任何数据,这样您就可以在脚本中使用一个简单的 JSON 对象。当然,如果您发现需要更多信息,可以通过额外的电话进行补充。

如果这不切实际,那么在 标记中“硬编码”JavaScript 对象是下一个最佳选择。当然,“硬编码”是从浏览器的角度来看的。实际内容肯定是由数据库中的服务器端脚本编写的。

I'd prefer a single AJAX call to fetch whatever data you know you need at the outset, so you can have a simple JSON object available in your script. You can, of course, supplement that with additional calls should you find you need more information.

If that's impractical, then "hardcoding" a JavaScript object in a <script>...</script> tag is the next best option. Of course, "hardcoding" is from the browser's perspective. The actual content would surely be written by server-side script from your database.

祁梦 2024-10-04 15:11:53

您可以使用的一种方法是自定义属性。我认为您将其称为微格式,但我不完全确定它们是否是同一件事,所以我在下面写了一个描述。

之前遇到过同样的问题,我基本上使用如下内容:

<div data-pid="1234">
    <a href="#" class="add-to-favourites">
        <img src="addToFavourites.png" />
    </a>
</div>

$("a.add-to-favourites").click(function() {
    $.load("/Favourites/Add.php?prodID="+$(this).parent().attr("data-pid"));
});

这应该完全符合你想要做的。我将 pid 放在 div 中而不是 a 标记中的原因是,您可以将所有其他产品信息放入div 以及用户可以执行的其他操作,例如使用 data-description 在鼠标悬停时显示工具提示,或使用 data-geo-x< 在地图上显示/code> 和 data-geo-y。当然,您可以将它们命名为任何您想要的名称。

支持/接受

这正在成为一种完全被接受的做你想做的事情的方式。 HTML 5 支持这一点,这正是您想要实现的目标。

所以 HTML 5 支持它,但是 HTML 4 呢?

它可能会使 HTML 4 失效,但世界正在朝着更大、更好的方向发展。较旧的浏览器(IE6 及更早版本、FF1 / 2、Opera 7 / 8 / 9)变得越来越不常见,因此这不应该成为问题。它实际上不会破坏旧版浏览器 - 该功能仍然有效。

重要有效性说明

确保将 data- 添加到属性名称前。这将使该属性在 HTML 5 中完全有效。

一些额外的提示

在 jQuery 1.5 中,我听到了 我的问题,您只需指定 attr("pid") 返回data-pid 的值。如果是这种情况,那么在实际属性名称之后命名属性名称的第二部分时我会小心(例如,使用 data-pid 而不是 data-id - 特别是如果指定了 id 属性,我不确定如果不这样做会产生什么影响,但最好首先避免这个问题。因此,该网站稍后会出现问题。

希望这就是您所寻找的。

One method you can use is custom attributes. I think you refer to this as micro-formats, but I am not entirely sure if they are the same thing so I have written a description below.

Having hit the same question before, I basically use something like the following:

<div data-pid="1234">
    <a href="#" class="add-to-favourites">
        <img src="addToFavourites.png" />
    </a>
</div>

$("a.add-to-favourites").click(function() {
    $.load("/Favourites/Add.php?prodID="+$(this).parent().attr("data-pid"));
});

This should do exactly what you want to do. The reason I have put the pid in the div, not the a tag, is that you can then place all the other product information within the div with other actions the user can take, for example displaying a tooltip on mouseover using data-description, or displaying on a map using data-geo-x and data-geo-y. Of course you can name these anything you want.

Support / Acceptance

This is becoming a perfectly accepted way to do what you want to do. HTML 5 supports this for precisely the kind of thing you are trying to achieve.

So it is supported by HTML 5, but what about HTML 4?

It may make HTML 4 invalid, but the world is moving on to bigger and better things. Older browsers (IE6 and before, FF1 / 2, Opera 7 / 8 / 9) are becoming less common so it shouldnt be a problem. It wont actually break older browsers - the functionality will still work.

Important validity note

Make sure you prepend the data- onto the attribute name. This will make the attribute perfectly valid in HTML 5.

A few extra hints

In jQuery 1.5, I have heard from an answer to my question that you can simply specify attr("pid") to return the value of data-pid. If this is the case then I would be careful when naming the second part of the attribute name after the name of an actual attribute (for example, instead of data-id, use data-pid - especially if the id attribute is specified. I am not sure what effect it would have if you didn't do this, but its better to avoid the problem in the first place than have issues with the site at a later date due to this.

Hope this is what you were looking for.

感性 2024-10-04 15:11:53

ASP.NET 提供了一种非常方便的方法来执行此操作。您可以简单地编写一个 JavaScript 对象。我确信其他模板引擎也提供类似的方法来做到这一点。

var person = {
    Name : <%= _person.Name %>,
    Age : <%= _person.Age %>
};

ASP.NET offers a very convenient way to do this. You can simply write a JavaScript object. I am sure other templating engines offer similar ways to do this.

var person = {
    Name : <%= _person.Name %>,
    Age : <%= _person.Age %>
};
┊风居住的梦幻卍 2024-10-04 15:11:53

我将实现一个在 document.ready 事件中初始化的 Javascript 单例 AppCacheManager。一点 JS oop,您就拥有了一个成熟的 OOP 数据存储。

每当需要信息时,您可以通过 Ajax / RESTful Web 服务加载它并将其缓存在 AppCache Manager 中。因此,您有 2 个缓存:1. 浏览器缓存(可能是由于 RESTful Web 服务 URL 缓存),以及 2:JS 缓存管理器。

您可以访问对 AppCacheManager 的所有请求,AppCacheManager 透明地获取新数据或返回缓存数据,以便客户端不需要了解任何缓存信息。

简而言之:

  • 编写一个 JS CacheManager
  • 不要一次获取全部数据,而是在需要时获取小部分数据并缓存它们
  • 为缓存管理器定义一个方便的接口

示例用法:

<a href="linkurl" onmouseover="CacheManagerFactory.getInstance().getTooltip('TooltipID');">linktext</a>

在 JS 中不引人注目是一件非常困难的事情,我很渴望对此也有所了解。

希望有帮助。

I would implement a Javascript singleton AppCacheManager that initializes in the document.ready event. A bit JS oop and you have a fully fledged OOP datastore.

Whenever information is needed, you load it through Ajax / RESTful Webservice and cache it in the AppCache Manager. So you have 2 caches: 1. Browser Cache, possible due to RESTful webservice URL caching, and 2: the JS Cache Manager.

You access all requests to the AppCacheManager which transparently fetches the new data or returns the cached data, so that the client doesnt need to know anything of the caching.

in short:

  • write a JS CacheManager
  • don't fetch the whole data at once but in small parts when needed and cache them
  • define a convenient interface for the cachemanager

Example usage:

<a href="linkurl" onmouseover="CacheManagerFactory.getInstance().getTooltip('TooltipID');">linktext</a>

Unobtrusiveness is a very difficult thing in JS and i'd be eager to know something about that, too.

hope that helped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文