Javascript 如何将数组从JS传递到PHP?
这是我的密码:Javascript 如何将数组从JS传递到PHP?,javascript,php,jquery,arrays,parameter-passing,Javascript,Php,Jquery,Arrays,Parameter Passing,这是我的密码: $(document).on('click', '#csv_export', function () { // I need to pass this array to where the form below submits var arr = ['item1', 'item2']; $('<form action="csv_export/person?filename=export.csv" method="P
$(document).on('click', '#csv_export', function () {
// I need to pass this array to where the form below submits
var arr = ['item1', 'item2'];
$('<form action="csv_export/person?filename=export.csv" method="POST"/>')
.append($('{!! csrf_field() !!}<input type="hidden" name="type" value="save">'))
.appendTo($(document.body)) //it has to be added somewhere into the <body>
.submit();
});
但我认为它有两个问题:
使用
JSON.stringify()
将数组转换为JSON。不要将输入构造为字符串,而是使用jQuery函数:
$('<form action="csv_export/person?filename=export.csv" method="POST"/>')
.append($('{!! csrf_field() !!}'))
.append($("<input>", {
type: 'hidden',
name: 'arr',
value: JSON.stringify(arr)
});
).appendTo('body')
.submit();
对于小数组,您可以只使用
{arr:arr}
,然后作为数组访问$\u POST['arr']
。但当您传递这样一个数组时,每个元素都成为一个单独的post参数,默认情况下PHP只允许1000个参数。您可以在php.ini
中对此进行更改,但对于这种情况,使用JSON可能是一个更简单的解决方案。您尝试了什么?通过将@hassan I的值设置为隐藏输入的值,可以复制它。但是在本例中,有字符长度限制。请注意,在您的问题中,您的问题不是将javascript数组传递给php,而是限制,对吗?提示:您没有使用res
执行任何操作,并且正在提交硬编码的值好的,我在服务器端得到了结果。结果就是一个JSON结构的字符串。我可以在服务器端将其作为数组获取吗?获取。。这对我来说也适用:(array)json_decode($\u POST['arr'],true)
您不需要(array)
,json_decode()
应该返回一个数组。
$('<form action="csv_export/person?filename=export.csv" method="POST"/>')
.append($('{!! csrf_field() !!}'))
.append($("<input>", {
type: 'hidden',
name: 'arr',
value: JSON.stringify(arr)
});
).appendTo('body')
.submit();
$.post('csv_export/person?filename=export.csv', { arr: JSON.stringify(arr) });