簡體   English   中英

如何將數組從JS傳遞到PHP?

[英]How can I pass an array from JS to PHP?

這是我的代碼:

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

正如我在代碼中評論的那樣,有一個arr ,我需要將其傳遞給表單指出的頁面。 我怎樣才能做到這一點?


注意,我可以將其放在表單中:

<input type="hidden" name="arr" value="'+arr+'">

但是我有兩個問題:

  1. 字符長度限制
  2. 結果將是一個字符串。 (雖然我需要在服務器端使用數組)

使用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();

在PHP腳本中,使用json_decode($_POST['arr'], true)獲取數組。

您還應該能夠使用AJAX:

$.post('csv_export/person?filename=export.csv', { arr: JSON.stringify(arr) });

對於小型數組,您可以只使用{ arr: arr } ,然后將$_POST['arr']作為數組訪問。 但是,當您傳遞這樣的數組時,每個元素將成為一個單獨的post參數,默認情況下,PHP僅允許1000個參數。 您可以在php.ini進行更改,但是對於這種情況,使用JSON可能是一個更簡單的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM