Javascript 如何在隐藏的输入字段中将我的数据设置为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7096965/
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 00:50:30  来源:igfitidea点击:

How can I set my data as JSON in a hidden input field

javascriptjson

提问by user882196

I have an input field like the one below

我有一个如下所示的输入字段

 <input type="hidden" value="" id="inputField">

Now I have list of products and for each product I have a checkbox. When a user clicks on the checkbox, I get the product id and name. Now I want to save it again in the hidden field like below

现在我有产品列表,对于每个产品,我都有一个复选框。当用户单击复选框时,我会得到产品 ID 和名称。现在我想再次将其保存在如下所示的隐藏字段中

<input type="hidden" 
       value="[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]"
       id="inputField"
>

My first question is how I can do this and how can I create the JSON?

我的第一个问题是如何做到这一点以及如何创建 JSON?

Secondly if the user again unchecks a product checkbox then I need to get the current hidden value and convert it into some data structure, remove the unchecked box id from the data structure and then save it again in the hidden field.

其次,如果用户再次取消选中产品复选框,那么我需要获取当前隐藏值并将其转换为某种数据结构,从数据结构中删除未选中的框 ID,然后再次将其保存在隐藏字段中。

Is there any library which does this job in JavaScript?

是否有任何库可以在 JavaScript 中完成这项工作?

回答by Diodeus - James MacFarlane

Using jQuery:

使用jQuery:

HTML:

HTML:

<input type="hidden" value='[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]'
 id="inputField">

JS:

JS:

var data = {}
data.products = jQuery.parseJSON($('#inputField').val())
alert(data.products[0].product_id) 

回答by Augustus Kling

The building block that you look for are JSON.stringifyand JSON.parse;

您要寻找的构建块是JSON.stringifyJSON.parse;

var stringData = '[{"product_id":123,"name":"stack"}, {"product_id":456,"name":"overflow"}]';
// Convert a string to an JavaScript object
var arrayData = JSON.parse(stringData);
// Convert a JavaScript object to a string
stringData = JSON.stringify(arrayData);

Now, whenever one of your checkboxes changes state, you'd get the object from the hidden field and modify it. After the modification of the object, you'd save the string back to the hidden field.

现在,每当您的复选框之一更改状态时,您都会从隐藏字段中获取对象并对其进行修改。修改对象后,您需要将字符串保存回隐藏字段。

To read and store the value from/to the hidden field:

要从/向隐藏字段读取和存储值:

var field = document.getElementById('inputField');
// Reading the value
stringData = field.getAttribute('value');
// Storing the value
field.setAttribute('value', stringData);

You still lack the modifications of your array which you would do similar to:

您仍然缺少对数组的修改,您将执行类似于:

// Adding a newly checked product
arrayData.push({
    product_id: …,
    name: …
});

// Removing a product from the list is more complicated
arrayData = arrayData.filter(function(product){
    var productIdToRemove = …;
    return product.product_id!==productIdToRemove;
});

Regarding libraries: Probably most do contain code to facilitate array manipulation and setting of form data. See the documentation of jQuery or prototype or the other answers for examples.

关于库:可能大多数都包含便于数组操作和表单数据设置的代码。有关示例,请参阅 jQuery 或原型的文档或其他答案。

Just a thought: Wouldn't it be simpler to discard the whole idea of using the hidden field and transfer the checkboxes to the server instead. If the checkbox was checked, use it, otherwise ignore the correlating product data.

只是一个想法:放弃使用隐藏字段的整个想法并将复选框转移到服务器不是更简单吗?如果选中该复选框,则使用它,否则忽略相关的产品数据。

回答by Cipi

As it is stated in other answers below, to convert JSON to string, use JSON.stringify() function like so:

正如下面其他答案中所述,要将 JSON 转换为字符串,请使用 JSON.stringify() 函数,如下所示:

var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);

And you get string representation of JSON object in var json. To do this other way round so you can update the actual JSON object contained in that string, you can use eval:

并且你得到 JSON 对象的字符串表示形式var json。要以相反的方式执行此操作,以便您可以更新该字符串中包含的实际 JSON 对象,您可以使用 eval:

var json_object = eval("("+json+")");

Now, original JSON object is recreated, and you can update it, and re-strigify it back to hidden field or some other var...

现在,重新创建原始 JSON 对象,您可以更新它,并将其重新定义为隐藏字段或其他一些变量...

回答by phihag

In JavaScript, just assign the value:

在 JavaScript 中,只需分配值:

var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);

In a server-side language, encode the JSON in HTML, for example with php's htmlspecialcharsor python's html.escape. The result will look like this:

在服务器端语言中,将 JSON 编码为 HTML,例如使用 phphtmlspecialchars或 python 的html.escape. 结果将如下所示:

<input type="hidden" id="inputField"
       value="[{&quot;product_id&quot;:123,&quot;name&quot;:&quot;stack&quot;}]">

回答by Norman Joyner

I am still a bit confused about your question, but if you are simply storing the name and id from the input checkboxes which are checked you can do this quite simply using jQuery.

我仍然对您的问题感到有些困惑,但是如果您只是从选中的输入复选框中存储名称和 ID,则可以使用 jQuery 轻松完成此操作。

var jsonArray = [];
$("input:checkbox:checked").each(function(){
    var jsonObj = {};
    jsonObj.product_id = $(this).attr("id");
    jsonObj.name = $(this).attr("name");
    jsonArray.push(jsonObj);
});

The variable jsonArraywill now hold a json string similar to the example you have posted. You can use JSON.stringify(jsonArray)to see this.

该变量jsonArray现在将包含一个类似于您发布的示例的 json 字符串。你可以用JSON.stringify(jsonArray)看这个。

There is no need to create the hidden field, holding this string as the value and trying to add and remove from it as checkbox states change. Simply execute the javascript when the page is ready to change via button click, etc.

无需创建隐藏字段,将这个字符串作为值,并在复选框状态改变时尝试添加和删除它。当页面准备好通过按钮单击等更改时,只需执行 javascript。

Best of luck.

祝你好运。

回答by SHIBIN

I would suggest to use the encodeURIComponentfunction. Together with the JSON.stringifywe should have something like the following:

我建议使用该encodeURIComponent功能。连同 ,JSON.stringify我们应该有如下内容:

var data= "{"name":"John"}";

var encodeddata encodeURIComponent(JSON.stringify(var data= "{"name":"John"}";
))

Now that value can be safely stored in an input hidden type like so:

现在该值可以安全地存储在输入隐藏类型中,如下所示:

<input type="hidden" value="'+encodeddata+'">

Now to read the data back we can do something like:

现在要读回数据,我们可以执行以下操作:

var data = JSON.parse(decodeURIComponent(value))

回答by FishBasketGordo

If you have a JSON object, save it to the hidden field using JSON.stringify:

如果您有 JSON 对象,请使用以下命令将其保存到隐藏字段JSON.stringify

var myObj = [{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}];
document.getElementById('inputField').value = JSON.stringify(myObj);

回答by user3813580

Add library

添加库

"<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>"

"<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>"

Use: ${fn:escapeXml(string1)}

使用:${fn:escapeXml(string1)}

input type="hidden" value="${fn:escapeXml(string1)}" id="inputField"

输入类型="隐藏"值="${fn:escapeXml(string1)}" id="inputField"