jQuery Javascript - 在隐藏字段中存储对象数组

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

Javascript - Storing array of objects in hidden field

jqueryarraysobjectpostserialization

提问by Adam Sasin

I need to store some input in a hidden field, so when I print the post-request, I get:

我需要在隐藏字段中存储一些输入,所以当我打印 post-request 时,我得到:

Array ( [0]=>1 [1]=>2 [2]=>3 )

I already tried:

我已经尝试过:

var elems = [];
elems.push['1'];
elems.push['2'];
elems.push['3'];

$('#input_hidden_field').val(elems);

But it does not work, anybody could help me with this?

但它不起作用,有人可以帮助我吗?

回答by empiric

You can parse your array into a JSON-string to store it:

您可以将数组解析为 JSON 字符串来存储它:

.push()is a function, therefore it needs ()and not the []array-syntax.

.push()是一个函数,因此它需要()而不是[]数组语法。

var elems = [];
elems.push('1');
elems.push('2');
elems.push('3');

$('#input_hidden_field').val(JSON.stringify(elems)); //store array

var value = $('#input_hidden_field').val(); //retrieve array
value = JSON.parse(value);

To create an object just change the definition of elemsand the storage of the values:

要创建对象,只需更改值的定义elems和存储:

var elems = {};
elems[0] = '1';
elems[1] = '2';
elems[2] = '3';

Demo

演示

Reference

参考

.stringify()

.stringify()

.parse()

.parse()

回答by Digelim

A better approach would be appending a new formdata for each value within an array.

更好的方法是为数组中的每个值附加一个新的表单数据。

JS

JS

var elems = [];
elems.push['1'];
elems.push['2'];
elems.push['3']; 

var fd = new FormData(document.getElementById("myform"));
for (var i = 0; i < elems.length; i++) {
   fd.append('elems[]', elems[i]);
}

HTML

HTML

<form action="./post-request.php" method="post" id="myform">
   <input type="hidden" name="elems[]" />
   <button type="submit" name="myarray">SEND</button>
</form>

PHP

PHP

<?php 

   if(isset($_POST['myarray']) {
      print_r($_POST['elems']); 
   }

回答by K15.Multik

JS

JS

var elems = [];
elems.push['1'];
elems.push['2'];
elems.push['3'];
$('#input_hidden_field').val(JSON.stringify(elems));

PHP

PHP

$elems = json_decode($_POST['hidden_input_name'], true);