简体   繁体   中英

Sending an array to PHP via AJAX

I declare my array:

p.myArray = [];

I add to the array in a loop:

 self.myArray.push($(this).data('id')); // [1,2,3,4]

I then send this via AJAX to PHP via POST:

$.ajax({
    url: '/gateway',
    data: {data: self.myArray}, 
    dataType: 'json',
    type: 'POST',
})

I was wondering, do I need to have a key/value pair? Can I just send through the array? Does it need serialising?

Passing an object to data will cause jQuery to serialise it for you.

The array will be available in $_POST['data'][]


It would be clearer if you didn't use the same name for different things.

data: { theArray: self.myArray }, 

goes to:

$_POST['theArray'][]

Note that if you are using dataType: 'json' your PHP script will have to return JSON serialised data or jQuery will ignore the response.

ie:

$myArray = $_POST['myArray'];
echo json_encode($myArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM