我怎么能以某种方式存储javascript数组对象,以便我以后可以使用它 [英] How i can store javascript array object saved somehow so that I can use it later
问题描述
我的情况如下:
我有一个id选择页面,用户可以从页面上显示的ID中选择id。当用户选择id时我将它们存储为隐藏输入字段中的逗号分隔值。
I have a id select page where user can select id from the shown ids on the page.When the user select the id i store them as a comma seperated value in a hidden input field.
<input type="hidden" values="234,678,987" />
我有一个按钮,在点击时弹出一个对话框,然后显示所选的ID。这里显示的ID来自隐藏字段。
现在我需要存储产品ID和名称。所以在这种情况下我应该怎么做因为现在我无法在隐藏的输入字段中保存这个数据结构。即使我使用javascript数组,如何保存该数组并将其用于将来进行显示。是否可以将数组对象保存在隐藏的输入字段中....稍后再将其作为数组对象检索...?
I have a button which on clicking pops up a dialog box which then displays the selected ids. The ids here shown I take from the hidden field. Now I have a requirement to store the product id and name.So probably in this case what should i do because now i can't be able to save this datastructure in hidden input field. Even if i use javascript array ,how can i save that array and use it future for displaying.Is it possible to save array object in hidden input field ....and retrieve it later as array object again...?
推荐答案
这是一个 JSFiddle 。
如果要将对象存储在输入字段中,可以使用 JSON.stringify()
:
If you want to store the object in an input field, you can use JSON.stringify()
:
//Pass your array (or JSON object) into JSON.stringify:
JSON.stringify([{id:1, product_id: 2, name: 'stack'},
{id: 2, product_id: 2, name: 'overflow'}] )
将产生:
"[{"id":1,"product_id":2,"name":"stack"},{"id":2,"product_id":2,"name":"overflow"}]"
您可以将此值存储在隐藏中字段(或数据属性):
You can store this value in a hidden field (or a data attribute):
<input type="hidden" id="project" value="[{'id':1,'product_id':2,'name':'stack"',{'id':2,'product_id':2,'name':'overflow'}]" />
显然,你可以结合这些步骤(或通过PHP / Rails / ...来实现) / p>
Obviously, you can combine these steps (or do it through PHP / Rails / ...)
$('#project').val(JSON.stringify([1,2,3]));
然后你可以使用例如jQuery解码它:
You can then decode this using, for instance, jQuery:
$.parseJSON($('#project').val());
这应该允许您使用您正在使用的过程,但在输入字段中存储Javascript对象。希望这会有所帮助!
This should allow you to use the process you are using, but store Javascript objects in your input fields. Hope this helps!
这篇关于我怎么能以某种方式存储javascript数组对象,以便我以后可以使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!