At one interview, once I attended, I was asked to create one java script based functionality in which I was said to create one form (say i.e first name, last name, email, age) and one listing(actually listing was kind of another form storing multiple entries) below this form. On submitting this form one new row was added to listing. However it is possible to remove any previously added listing row. and after adding removing, finally need to store this final state of listing. ( Kind of form post and server side scripting comes into picture )
在一次采访中,我被要求创建一个基于java脚本的功能,在这个功能中,我被要求创建一个表单。e名、姓、电子邮件、年龄)和一个列表(实际上列表是另一种存储多个条目的表单)。在提交这个表单时,一个新的行被添加到列表中。但是,可以删除任何先前添加的清单行。在添加删除之后,最终需要存储这个列表的最终状态。(出现了表单post和服务器端脚本)
So what I did that, On Form submit, adding a new <tr>
row in listing table at the same time I serialized all form data except submit button using jQuery serialize and stored it in one hidden element of listing form.
在表单提交上,我在列表表中添加了一个新的行,与此同时,我使用jQuery序列化来序列化除了提交按钮之外的所有表单数据,并将其存储在列表表单的一个隐藏元素中。
On removing listing row, I was removing <tr>
row along with respective hidden element for the same row.
在删除清单行时,我删除了同一行的行以及相应的隐藏元素。
All was working like great without any error. But the interviewer asked me that "The approach I used (hidden elements) was really proper?".
一切都很顺利,没有任何差错。但是面试官问我“我使用的方法(隐藏的元素)真的是正确的吗?”
I replied, I could have used json? but Could not crack interview. So I want to know what is best approach that We can use to store data in such conditions?
我回答,我可以用json?但无法进行面试。我想知道在这种情况下,我们可以用什么方法来存储数据?
8 个解决方案
#1
7
Another approach for client-side is to keep a list of objects separately and only store the reference to each item inside a property of your DOM element. This approach is very similar to what jQuery's $.fn.data()
provides and has these advantages:
客户端的另一种方法是单独保存一个对象列表,并且只将引用存储在DOM元素的属性中。这种方法与jQuery $.fn.data()提供的非常相似,并且具有以下优点:
-
You don't have to serialize anything, the data stays in its native format; it should be said that you could have achieved this by adding a property as well.
你不需要序列化任何东西,数据保持其本地格式;应该说,你也可以通过添加属性来实现这一点。
-
All your data is kept in one place instead of scattered around in the DOM.
所有数据都保存在一个地方,而不是分散在DOM中。
This is an example implementation:
这是一个示例实现:
(function(ns) {
var entries = {},
entryId = 1;
ns.Entries = {
addEntry: function(data) {
entries[entryId] = data;
return entryId++;
},
getEntryById: function(id) {
return entries[id] || null;
}
};
}(this));
Calling Entries.addEntry
returns an identifier that you can store in one of the DOM element's properties:
调用条目。addEntry返回一个标识符,您可以将该标识符存储在DOM元素的一个属性中:
tr.entryId = Entries.addEntry(data);
Later you can use that entryId
property to find the corresponding data in the entry list and use it.
之后,您可以使用entryId属性在条目列表中找到相应的数据并使用它。
var data = Entries.getEntryById(tr.entryId);
演示
Of course, this particular functionality can also be solved server-side by using sessions.
当然,这个特定的功能也可以通过使用会话来解决服务器端。
#2
6
Thanks to HTML5, we now have the ability to embed custom data attributes on all HTML elements. These new custom data attributes consist of two parts:
多亏了HTML5,我们现在能够在所有HTML元素上嵌入自定义数据属性。这些新的自定义数据属性包括两个部分:
- Attribute Name The data attribute name must be at least one character long and must be prefixed with 'data-'. It should not contain any uppercase letters.
- 属性名称数据属性名称必须至少有一个字符长,并且必须以“data-”为前缀。它不应该包含任何大写字母。
- Attribute Value The attribute value can be any string.
- 属性值属性值可以是任何字符串。
Using this syntax, we can add application data to our markup as shown below:
使用这种语法,我们可以将应用程序数据添加到我们的标记中,如下所示:
<ul id="vegetable-seeds">
<li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>
<li data-spacing="30cm" data-sowing-time="February to March">Celery</li>
<li data-spacing="3cm" data-sowing-time="March to September">Radishes</li>
</ul>
We can now use this stored data in our site’s JavaScript to create a richer, more engaging user experience. Imagine that when a user clicks on a vegetable a new layer opens up in the browser displaying the additional seed spacing and sowing instructions. Thanks to the data- attributes we’ve added to our <li>
elements, we can now display this information instantly without having to worry about making any Ajax calls and without having to make any server-side database queries.
我们现在可以在我们的网站的JavaScript中使用这些存储数据来创建更丰富、更吸引人的用户体验。想象一下,当用户点击蔬菜时,浏览器会打开一个新图层,显示额外的种子间距和播种指令。由于我们在
source: HTML5 Doctor
来源:HTML5的医生
There are other methods too I believe.
我相信还有其他的方法。
#3
2
Actually instead of using hidden elements , you can add data to the html elements using jQuery. This is a better approach to make your data a little less obvious/direct to the users. Check the data() in jQuery.
实际上,您可以使用jQuery向html元素添加数据,而不是使用隐藏的元素。这是一种更好的方法,可以使您的数据对用户不那么明显/直接。用jQuery检查数据()。
#4
0
Nothing wrong with storing data client-side if the user can be trusted with it and nothing terrible happens to your system when he messes with it.
如果用户可以信任数据,那么在客户端存储数据没有任何问题,当用户使用数据时,系统也不会发生什么糟糕的事情。
Only problem I can see with using hidden fields (or cookies) is that they get sent with every request, which might waste bandwidth. Not sure if that applies to your case, probably not, because you say you just submit once when all is done.
使用隐藏字段(或cookie)的唯一问题是,它们会随每个请求一起发送,这可能会浪费带宽。不确定这是否适用于您的案例,可能不适用,因为您说您在完成所有工作后只提交一次。
#5
0
The problem with solutions that 'just work' is that they are not abstract enough and therefore tend to cause problems in the future. Consider your example; should you decide to store the temporary data in Local Storage (to allow users close their browser and return to it later), you'd have to rewrite how you store your data. If you stored it in a variable, you'd be able to add 'Save to Local Storage' just as easily as 'Submit to server' or 'Pass to Any Other Function' functionality. Your 'hidden element' approach would have to be rewritten for any purpose except posting to service.
“只工作”的解决方案的问题在于它们不够抽象,因此在未来容易产生问题。考虑你的例子;如果您决定将临时数据存储在本地存储中(允许用户关闭浏览器并稍后返回),那么您必须重写如何存储数据。如果您将它存储在一个变量中,您将能够添加“Save to Local Storage”,就像“Submit to server”或“Pass to Any Other Function”一样简单。您的“隐藏元素”方法必须重写,以达到除了发布到服务之外的任何目的。
#6
0
To start with, multiple forms on one page are wrong - it's data loss antipattern. The correct approach would be to place everything into one form. This way, it would work even without JS and you could use JS only to improve usability, not to provide basic functionality. This solution would degrade gracefully an it would be easy to debug and maintain.
首先,一个页面上的多个表单是错误的——它是数据丢失反模式。正确的方法是把所有东西都放在一个表单中。这样,即使没有JS,它也可以工作,您只能使用JS来提高可用性,而不能提供基本的功能。该解决方案将优雅地降级,而it将易于调试和维护。
Of course, saving the data in hidden field is a valid technique.
当然,在隐藏字段中保存数据是一种有效的技术。
#7
0
By writing submitted data into the form itself, and reading again from it, you've tied these two elements together - they are said to be tightly coupled.
通过将提交的数据写入表单本身,并再次读取它,您将这两个元素结合在一起——它们被认为是紧密耦合的。
What word happen if another requirement came through to displaye previously submitted data in the table also? Or to put the form on a separate page?
如果displaye之前在表中提交的数据也遇到了另一个需求,会发生什么情况?或者把表格放在一个单独的页面上?
If you take a more MVC approach, you can separate out the logic for the various parts - reading, writing and sending data. For example, as you said, writing and reading from a JSON model. This would make each aspect more readily extensible in the future.
如果采用更多的MVC方法,您可以将不同部分(读取、写入和发送数据)的逻辑分离开来。例如,正如您所说,从JSON模型编写和读取。这将使每个方面在将来更容易扩展。
#8
0
I will not answer your question directly but will focus on interview and method you chose.
我不会直接回答你的问题,而是将重点放在你选择的面试和方法上。
I would say you chose wrong way and well known IT company you applied this solution for can have problems.
我想说的是,你选择了错误的方式,而且你所应用的IT公司都是众所周知的。
You chose the way to store everything on client's side, but you shouldn't! As your client can lose a lot of data this way, because imagine the case when your listing form will never be sent? User will just forget to hit send (never trust user!). Then you lose everything... whole progress of your work... and let's say you've already added 50 listing items...
你选择了在客户端存储所有东西的方法,但你不应该这样做!因为您的客户端可能会以这种方式丢失大量数据,因为想象一下永远不会发送您的列表表单的情况?用户只会忘记点击发送(绝不信任用户!)然后你失去一切…你的工作进展……假设您已经添加了50个列表项……
Also adding items like this can easily make your session expired (no requests to the server) and no data will be saved, because user will have to log in again. And you will have to handle it as well, or you will lose everything!
另外,添加这样的项可以很容易地使您的会话过期(没有对服务器的请求),并且不会保存任何数据,因为用户将不得不再次登录。你也得处理好,否则你会失去一切!
Sorry for exclamation marks, but I think data is crucial (especially for your client) so do not ever offer solutions which can make client losing it somehow.
很抱歉,这里有感叹号,但是我认为数据是非常重要的(尤其是你的客户),所以不要提供任何可能导致客户丢失的解决方案。
So:
所以:
It's not bad to store data in HTML elements, but you need to apply this solution very carefully.
在HTML元素中存储数据并不是坏事,但是您需要非常小心地应用这个解决方案。
#1
7
Another approach for client-side is to keep a list of objects separately and only store the reference to each item inside a property of your DOM element. This approach is very similar to what jQuery's $.fn.data()
provides and has these advantages:
客户端的另一种方法是单独保存一个对象列表,并且只将引用存储在DOM元素的属性中。这种方法与jQuery $.fn.data()提供的非常相似,并且具有以下优点:
-
You don't have to serialize anything, the data stays in its native format; it should be said that you could have achieved this by adding a property as well.
你不需要序列化任何东西,数据保持其本地格式;应该说,你也可以通过添加属性来实现这一点。
-
All your data is kept in one place instead of scattered around in the DOM.
所有数据都保存在一个地方,而不是分散在DOM中。
This is an example implementation:
这是一个示例实现:
(function(ns) {
var entries = {},
entryId = 1;
ns.Entries = {
addEntry: function(data) {
entries[entryId] = data;
return entryId++;
},
getEntryById: function(id) {
return entries[id] || null;
}
};
}(this));
Calling Entries.addEntry
returns an identifier that you can store in one of the DOM element's properties:
调用条目。addEntry返回一个标识符,您可以将该标识符存储在DOM元素的一个属性中:
tr.entryId = Entries.addEntry(data);
Later you can use that entryId
property to find the corresponding data in the entry list and use it.
之后,您可以使用entryId属性在条目列表中找到相应的数据并使用它。
var data = Entries.getEntryById(tr.entryId);
演示
Of course, this particular functionality can also be solved server-side by using sessions.
当然,这个特定的功能也可以通过使用会话来解决服务器端。
#2
6
Thanks to HTML5, we now have the ability to embed custom data attributes on all HTML elements. These new custom data attributes consist of two parts:
多亏了HTML5,我们现在能够在所有HTML元素上嵌入自定义数据属性。这些新的自定义数据属性包括两个部分:
- Attribute Name The data attribute name must be at least one character long and must be prefixed with 'data-'. It should not contain any uppercase letters.
- 属性名称数据属性名称必须至少有一个字符长,并且必须以“data-”为前缀。它不应该包含任何大写字母。
- Attribute Value The attribute value can be any string.
- 属性值属性值可以是任何字符串。
Using this syntax, we can add application data to our markup as shown below:
使用这种语法,我们可以将应用程序数据添加到我们的标记中,如下所示:
<ul id="vegetable-seeds">
<li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>
<li data-spacing="30cm" data-sowing-time="February to March">Celery</li>
<li data-spacing="3cm" data-sowing-time="March to September">Radishes</li>
</ul>
We can now use this stored data in our site’s JavaScript to create a richer, more engaging user experience. Imagine that when a user clicks on a vegetable a new layer opens up in the browser displaying the additional seed spacing and sowing instructions. Thanks to the data- attributes we’ve added to our <li>
elements, we can now display this information instantly without having to worry about making any Ajax calls and without having to make any server-side database queries.
我们现在可以在我们的网站的JavaScript中使用这些存储数据来创建更丰富、更吸引人的用户体验。想象一下,当用户点击蔬菜时,浏览器会打开一个新图层,显示额外的种子间距和播种指令。由于我们在
source: HTML5 Doctor
来源:HTML5的医生
There are other methods too I believe.
我相信还有其他的方法。
#3
2
Actually instead of using hidden elements , you can add data to the html elements using jQuery. This is a better approach to make your data a little less obvious/direct to the users. Check the data() in jQuery.
实际上,您可以使用jQuery向html元素添加数据,而不是使用隐藏的元素。这是一种更好的方法,可以使您的数据对用户不那么明显/直接。用jQuery检查数据()。
#4
0
Nothing wrong with storing data client-side if the user can be trusted with it and nothing terrible happens to your system when he messes with it.
如果用户可以信任数据,那么在客户端存储数据没有任何问题,当用户使用数据时,系统也不会发生什么糟糕的事情。
Only problem I can see with using hidden fields (or cookies) is that they get sent with every request, which might waste bandwidth. Not sure if that applies to your case, probably not, because you say you just submit once when all is done.
使用隐藏字段(或cookie)的唯一问题是,它们会随每个请求一起发送,这可能会浪费带宽。不确定这是否适用于您的案例,可能不适用,因为您说您在完成所有工作后只提交一次。
#5
0
The problem with solutions that 'just work' is that they are not abstract enough and therefore tend to cause problems in the future. Consider your example; should you decide to store the temporary data in Local Storage (to allow users close their browser and return to it later), you'd have to rewrite how you store your data. If you stored it in a variable, you'd be able to add 'Save to Local Storage' just as easily as 'Submit to server' or 'Pass to Any Other Function' functionality. Your 'hidden element' approach would have to be rewritten for any purpose except posting to service.
“只工作”的解决方案的问题在于它们不够抽象,因此在未来容易产生问题。考虑你的例子;如果您决定将临时数据存储在本地存储中(允许用户关闭浏览器并稍后返回),那么您必须重写如何存储数据。如果您将它存储在一个变量中,您将能够添加“Save to Local Storage”,就像“Submit to server”或“Pass to Any Other Function”一样简单。您的“隐藏元素”方法必须重写,以达到除了发布到服务之外的任何目的。
#6
0
To start with, multiple forms on one page are wrong - it's data loss antipattern. The correct approach would be to place everything into one form. This way, it would work even without JS and you could use JS only to improve usability, not to provide basic functionality. This solution would degrade gracefully an it would be easy to debug and maintain.
首先,一个页面上的多个表单是错误的——它是数据丢失反模式。正确的方法是把所有东西都放在一个表单中。这样,即使没有JS,它也可以工作,您只能使用JS来提高可用性,而不能提供基本的功能。该解决方案将优雅地降级,而it将易于调试和维护。
Of course, saving the data in hidden field is a valid technique.
当然,在隐藏字段中保存数据是一种有效的技术。
#7
0
By writing submitted data into the form itself, and reading again from it, you've tied these two elements together - they are said to be tightly coupled.
通过将提交的数据写入表单本身,并再次读取它,您将这两个元素结合在一起——它们被认为是紧密耦合的。
What word happen if another requirement came through to displaye previously submitted data in the table also? Or to put the form on a separate page?
如果displaye之前在表中提交的数据也遇到了另一个需求,会发生什么情况?或者把表格放在一个单独的页面上?
If you take a more MVC approach, you can separate out the logic for the various parts - reading, writing and sending data. For example, as you said, writing and reading from a JSON model. This would make each aspect more readily extensible in the future.
如果采用更多的MVC方法,您可以将不同部分(读取、写入和发送数据)的逻辑分离开来。例如,正如您所说,从JSON模型编写和读取。这将使每个方面在将来更容易扩展。
#8
0
I will not answer your question directly but will focus on interview and method you chose.
我不会直接回答你的问题,而是将重点放在你选择的面试和方法上。
I would say you chose wrong way and well known IT company you applied this solution for can have problems.
我想说的是,你选择了错误的方式,而且你所应用的IT公司都是众所周知的。
You chose the way to store everything on client's side, but you shouldn't! As your client can lose a lot of data this way, because imagine the case when your listing form will never be sent? User will just forget to hit send (never trust user!). Then you lose everything... whole progress of your work... and let's say you've already added 50 listing items...
你选择了在客户端存储所有东西的方法,但你不应该这样做!因为您的客户端可能会以这种方式丢失大量数据,因为想象一下永远不会发送您的列表表单的情况?用户只会忘记点击发送(绝不信任用户!)然后你失去一切…你的工作进展……假设您已经添加了50个列表项……
Also adding items like this can easily make your session expired (no requests to the server) and no data will be saved, because user will have to log in again. And you will have to handle it as well, or you will lose everything!
另外,添加这样的项可以很容易地使您的会话过期(没有对服务器的请求),并且不会保存任何数据,因为用户将不得不再次登录。你也得处理好,否则你会失去一切!
Sorry for exclamation marks, but I think data is crucial (especially for your client) so do not ever offer solutions which can make client losing it somehow.
很抱歉,这里有感叹号,但是我认为数据是非常重要的(尤其是你的客户),所以不要提供任何可能导致客户丢失的解决方案。
So:
所以:
It's not bad to store data in HTML elements, but you need to apply this solution very carefully.
在HTML元素中存储数据并不是坏事,但是您需要非常小心地应用这个解决方案。