Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将数组从JS传递到PHP?_Javascript_Php_Jquery_Arrays_Parameter Passing - Fatal编程技术网

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