如何通过 JQuery Post 传递一个 Javascript 数组,以便它的所有内容都可以通过 PHP $_POST 数组访问?

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

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

phpjavascriptjquery

提问by PleaseHelpMe

How can I pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

如何通过 JQuery Post 传递 Javascript 数组,以便可以通过 PHP $_POST 数组访问其所有内容?

Please show an example of code that would do the trick.

请展示一个可以解决问题的代码示例。

Thanks!

谢谢!

回答by prodigitalson

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

如果你想传递一个 JavaScript 对象/哈希(即 PHP 中的关联数组),那么你可以这样做:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

如果你想传递一个实际的数组(即 PHP 中的索引数组),那么你可以这样做:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

如果你想传递一个 JavaScript 数组,那么你可以这样做:

$.post('/url/to/page', {'someKeyName': variableName});

回答by Groovetrain

This is fairly straightforward. In your JS, all you would do is this or something similar:

这是相当简单的。在你的 JS 中,你要做的就是这个或类似的东西:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

在您的 php 页面中,数组形式的值将通过$_POST['array1'].

references

参考

回答by Rui

Here it goes an example:

这是一个例子:

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Hope it helps.

希望能帮助到你。

回答by Sahithi

I think we should sent in this format

我认为我们应该以这种格式发送

var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});

Its already mentioned in Pass array to mvc Action via AJAX

它已经在通过 AJAX 将数组传递给 mvc Action 中提到

It worked for me

它对我有用