简体   繁体   English

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

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

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. 当用户点击复选框时,我会获得产品ID和名称。 Now I want to save it again in the hidden field like below 现在我想再次将它保存在隐藏字段中,如下所示

<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中完成这项工作的库?

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) 

The building block that you look for are JSON.stringify and 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. 如果选中该复选框,请使用它,否则忽略相关的产品数据。

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 htmlspecialchars or python's html.escape . 在服务器端语言中,用HTML编码JSON,例如使用php的htmlspecialchars或python的html.escape The result will look like this: 结果将如下所示:

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

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 . 并且您在var json获得JSON对象的字符串表示形式。 To do this other way round so you can update the actual JSON object contained in that string, you can use eval: 要以其他方式执行此操作以便您可以更新该字符串中包含的实际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对象,您可以更新它,并将其重新格式化回隐藏字段或其他一些变量...

I would suggest to use the encodeURIComponent function. 我建议使用encodeURIComponent函数。 Together with the JSON.stringify we should have something like the following: 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))

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 jsonArray will now hold a json string similar to the example you have posted. 变量jsonArray现在将保存一个类似于您发布的示例的json字符串。 You can use JSON.stringify(jsonArray) to see this. 您可以使用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. 祝你好运。

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);

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" input type =“hidden”value =“$ {fn:escapeXml(string1)}”id =“inputField”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM