I have the following piece of jQuery code:
function saveSchedule()
{
var events = [];
$('ul#schedule-list').children().each(function() {
events.push($(this).attr('value'));
});
jQuery.each(events, function()
{
alert(this);
});
$.post("schedule_service.php?action=save_schedule",
{ events: events, studentid: $('#student').val() },
function(data) {
alert(data);
}, 'json');
}
Which gets all the 'values' from a list on my page, and puts them into the events array.
Then, below I pass in that array plus a studentid into the data section of my $.post call.
However, when I receive this array on my PHP side, it seems to be a singular value:
<?php
include_once('JSON.php');
$json = new Services_JSON();
if ($_GET['action'] == 'save_schedule')
{
$event_list = $_POST['events'];
echo $json->encode($event_list);
exit;
}
?>
(note: I'm using an older version of PHP, hence the JSON.php library.)
Now, all this ever returns is "14", which is the last event in the events array.
Post:
Response:
How am I handling passing the array in my $.post wrong?
It may seem silly, but try this:
$.post("schedule_service.php?action=save_schedule",
{ 'events[]': events, studentid: $('#student').val() },
function(data) {
alert(data);
}, 'json');
PHP will parse the key name events[]
into an actual array inside php automatically...
You can pass the array elements as a string comprising of all the elements concatenated by a character. Then you can split the array in your php code and extract the values there.
Use join() to join the elements of an array.
join(separator);
separator:
Specifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma.
Use explode() on the PHP side to turn the **join()**ed string back together.
Why not use JSON? Pass the JavaScript array as a JSON object and parse it in PHP.
信不信由你,只需要在$.post
请求中使用'events[]': events
,而不要使用events: events
(不带括号)。
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.