Javascript 在 DOM 中存储 JSON 的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7529173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:36:24  来源:igfitidea点击:

Best practices for Storing JSON in DOM

htmljsondomjavascript

提问by Goran Obradovic

I want to render some json data using HTML template.

我想使用 HTML 模板呈现一些 json 数据。

I haven't started implementing anything yet, but I would like to be able to "set" values of data from json to html element which contains template for one record, or to render some collection of items using some argument which is template html for each item, but also to be able to get JSON object back in same format as source JSON which was used to render item (I want my initial JSON to contain some more information about behavior of record row, without the need to make ajax request to check if user can or can't do something with this record, and not all of this info is visible in template).

我还没有开始实现任何东西,但我希望能够将数据的值从 json“设置”到包含一条记录模板的 html 元素,或者使用模板 html 的某个参数呈现一些项目集合每个项目,而且还能够以与用于呈现项目的源 JSON 相同的格式获取 JSON 对象(我希望我的初始 JSON 包含有关记录行行为的更多信息,而无需向检查用户是否可以使用此记录执行某些操作,并且并非所有这些信息都在模板中可见)。

I know that I could make hidden form with an input element for each property of object to store, and mapper function to/from JSON, but it sounds like overkill to me, and I don't like that, I want some lighter "envelope".

我知道我可以为要存储的对象的每个属性创建一个带有输入元素的隐藏表单,以及与 JSON 之间的映射函数,但这对我来说听起来有点矫枉过正,我不喜欢那样,我想要一些更轻的“信封” ”。

I was wondering is there some JS library that can "serialize" and "deserialize" JSON objects into html so I can store it somewhere in DOM (i.e. in element which contains display for data, but I want to be able to store additional attributes which don't have to be shown as form elements)?

我想知道是否有一些 JS 库可以将 JSON 对象“序列化”和“反序列化”到 html 中,以便我可以将它存储在 DOM 中的某个位置(即包含数据显示的元素中,但我希望能够存储其他属性不必显示为表单元素)?

UPDATEAs first answer suggested storing JSON in global variable, I also have thought about that, and my "best" mental solution was to make JavaScript module (or jQuery plugin) which would do "mapping" of JSON to html, and if not possible to store values in html then it can store them in internal variable, so when I want to "get" data from html element it can pull it from its local copy. I want to know is there better way for this? If there is some library that stores this info in variable, but does real-time "binding" of that data with html, I would be very happy with that.

更新作为第一个答案建议将 JSON 存储在全局变量中,我也考虑过这一点,我的“最佳”心理解决方案是制作 JavaScript 模块(或 jQuery 插件),它可以将 JSON“映射”到 html,如果不可能要将值存储在 html 中,然后它可以将它们存储在内部变量中,因此当我想从 html 元素“获取”数据时,它可以从其本地副本中提取数据。我想知道有没有更好的方法?如果有一些库将这些信息存储在变量中,但使用 html 实时“绑定”该数据,我会很高兴。

UPDATE 2This is now done using http://knockoutjs.com/, no need to keep json in DOM anymore, knockout does the JSON<=>HTML mapping automatically

更新 2现在使用http://knockoutjs.com/完成,不再需要将 json 保留在 DOM 中,knockout 会自动执行 JSON<=>HTML 映射

回答by graphicdivine

Why not store it as nature intended: as a javascript object? The DOM is a horrible place.

为什么不将其存储为自然意图:作为 javascript 对象?DOM 是一个可怕的地方。

That said, jQuery has the data methodthat allows just this.

也就是说,jQuery 有允许这样做的数据方法

回答by Raynos

So you want to keep a reference to the JSON data that created your DOMFragment from a template?

因此,您想保留对从模板创建 DOMFragment 的 JSON 数据的引用吗?

Let's say you have a template function that takes a template and data and returns a DOM node.

假设您有一个模板函数,它接受模板和数据并返回一个 DOM 节点。

var node = template(tmpl, json);
node.dataset.origJson = json;
node.dataset.templateName = tmpl.name;

You can store the original json on the dataset of a node. You may need a dataset shim though.

您可以将原始 json 存储在节点的数据集上。不过,您可能需要一个数据集垫片。

There is also no way to "map" JSON to HTML without using a template engine. Even then you would have to store the template name in the json data (as meta data) and that feels ugly to me.

如果不使用模板引擎,也无法将 JSON“映射”到 HTML。即便如此,您也必须将模板名称存储在 json 数据中(作为元数据),这对我来说很难看。

回答by Allen Tellez

I have done this in the past as well in a couple of different ways.

我过去也曾以几种不同的方式这样做过。

The $('selector').dataidea is probably one of the most useful techniques. I like this way of storing data because I can store the data in a logical, intuitive and orderly fashion.

这个$('selector').data想法可能是最有用的技术之一。我喜欢这种存储数据的方式,因为我可以以合乎逻辑、直观和有序的方式存储数据。

Let's say you have an ajax call that retrieves 3 articles on page load. The articles may contain data relating to the headline, the date/time, the source etc. Let's further assume you want to show the headlines and when a headline is clicked you want to show the full article and its details.

假设您有一个 ajax 调用,它在页面加载时检索 3 篇文章。文章可能包含与标题、日期/时间、来源等相关的数据。让我们进一步假设您想要显示标题,并且当点击标题时您想要显示完整的文章及其详细信息。

To illustrate the concept a bit let's say we retrieve json looking something like:

为了稍微说明这个概念,假设我们检索 json 看起来像:

{
    articles: [
        {
            headline: 'headline 1 text',
            article: 'article 1 text ...',
            source: 'source of the article, where it came from',
            date: 'date of the article'
        },
        {
            headline: 'headline 2 text',
            article: 'article 2 text ...',
            source: 'source of the article, where it came from',
            date: 'date of the article'
        },
        {
            headline: 'headline 3 text',
            article: 'article 3 text ...',
            source: 'source of the article, where it came from',
            date: 'date of the article'
        }
    ]
}

From an ajax call like this . . .

来自这样的 ajax 调用。. .

$.ajax({
    url: "news/getArticles",
    data: { count: 3, filter: "popular" }, 
    success: function(data){

        // check for successful data call
        if(data.success) {

            // iterate the retrieved data
            for(var i = 0; i < data.articles.length; i++) {
                var article = data.articles[i];

                // create the headline link with the text on the headline
                var $headline = $('<a class="headline">' + article.headline + '</a>');

                // assign the data for this article's headline to the `data` property
                // of the new headline link
                $headline.data.article = article;

                // add a click event to the headline link
                $headline.click(function() {
                    var article = $(this).data.article;

                    // do something with this article data
                });

                // add the headline to the page
                $('#headlines').append($headline);
            }
        } else {
            console.error('getHeadlines failed: ', data);
        }
    }
});

The idea being we can store associated data to a dom element and access/manipulate/delete that data at a later time when needed. This cuts down on possible additional data calls and effectively caches data to a specific dom element.

我们的想法是我们可以将关联的数据存储到 dom 元素,并在以后需要时访问/操作/删除该数据。这减少了可能的额外数据调用,并有效地将数据缓存到特定的 dom 元素。

anytime after the headline link is added to the document the data can be accessed through a jquery selector. To access the article data for the first headline:

将标题链接添加到文档后,可以随时通过 jquery 选择器访问数据。要访问第一个标题的文章数据:

$('#headlines .headline:first()').data.article.headline
$('#headlines .headline:first()').data.article.article
$('#headlines .headline:first()').data.article.source
$('#headlines .headline:first()').data.article.date

Accessing your data through a selector and jquery object is sorta neat.

通过选择器和 jquery 对象访问您的数据是相当整洁的。

回答by Mircea Soaica

I don't think there are any libraries that store json in dom.

我认为没有任何库将 json 存储在 dom 中。

You could render the html using the data from json and keep a copy of that json variable as a global variable in javascript.

您可以使用来自 json 的数据呈现 html,并将该 json 变量的副本保留为 javascript 中的全局变量。