开发者

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

开发者 https://www.devze.com 2023-02-22 19:21 出处:网络
How can I pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

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

Please show an ex开发者_运维技巧ample of code that would do the trick.

Thanks!


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

$.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:

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

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

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


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

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'].

references

  • jQuery post()
  • jQuery ajax()


Here it goes an example:

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

Hope it helps.


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

It worked for me

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号