简体   繁体   English

如何在隐藏字段中检索数组

[英]how to retrieve array in hidden field

I am storing my array in hidden field 我将数组存储在隐藏字段中

var myarray = [];

if ($(this).prop('checked')) {
    myarray.push(val);
    $('#myhidden').val(JSON.stringify(myarray));

}

how can I retrieve that array ? 我如何检索该数组? because I want that array to past it to other page using jquery.ajax 因为我想使用jquery.ajax将数组粘贴到其他页面

I tried this 我试过了

var retarray  = $('#myhidden').val();

["110","118"]

when I send that using jquery.ajax 当我使用jquery.ajax发送时

 $.ajax({ type: 'post', dataType: 'json', url: 'tootherpage.php', data: 'param1=' + param1 + '&param_array=' + retarray, success: function(data) { } }); 

it gives me error because it is not an array. 它给我错误,因为它不是数组。

Thank you in advance. 先感谢您。

You're converting your array to a string here: 您正在将数组转换为字符串:

$('#myhidden').val(JSON.stringify(myarray));

If you need it to be an array, then you need to parse this array back from the string 如果需要将其作为数组,则需要从字符串中解析出该数组

var retarray  = JSON.parse($('#myhidden').val());

for example: 例如:

var array = [1,2,3,4];  // create an array
var stringarray = JSON.stringify(array);  // convert array to string
var array2 = JSON.parse(stringarray);  // convert string to array

尝试这个

 var retarray = encodeURIComponent($('#myhidden').val());

You can do this : 你可以这样做 :

$('#myhidden').val(myarray.split("|")); //set "0|1".split("|") - creates array like [0,1] 
myarray = $('#myhidden').val().join("|"); //get [0,1].join("|") - creates string like "0|1"

"|" “ |” is a symbol that is not present in array, it is important. 是数组中不存在的符号,这一点很重要。

Your ajax request is is using the method POST and you have specified a data type of json which means your http request is sending json in the body. 您的ajax请求正在使用POST方法,并且您已将数据类型指定为json ,这意味着您的http请求正在正文中发送json

So you can send your whole request message as json , like this: 因此,您可以将整个请求消息作为json发送,如下所示:

// get json from input
var retarray  = $('#myhidden').val();

// parse json into js
var arr = JSON.parse(retarray);

// create your request data
var data = { param1: param1, param_array: arr };

// stringify
var json = JSON.stringify(data);

$.ajax({
  type: 'post',
  dataType: 'json',
  url: 'tootherpage.php',
  data: json, // the json we created above
  success: function(data) {


  }

});

Then in your php script you can deserialize the json message to a php object like so: 然后在您的php脚本中,您可以将json消息反序列化为php对象,如下所示:

$json = file_get_contents('php://input'); $obj = json_decode($json)

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

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