简体   繁体   中英

Sending array via Ajax fails

var labels = new Array();

<?php foreach($crud_data as $cd ) { ?>
  labels['<?php echo $cd['name'] ; ?>'] = '<?php echo $cd['label'] ; ?>';
<?php } ?>

$.post('url.php' , { labels:labels} );

Why can I not send labels array like this? It doesn't show anything in Firebug.

My console.log(labels) result:

[]

avatar
"avatar"

email
"email"

id
"id"

name
"name"

password
"password"

if i populate array like this

<?php foreach($crud_data as $cd ) { ?>
  labels.push('<?php echo $cd['label'] ; ?>');
<?php } ?>

$.post('url.php' , { labels:labels} );

it works fine !

Oh I see now. If you have string keys, you have to use an object, not an array:

var labels = {};

Arrays in JavaScript are supposed to only hold elements with numeric keys. While you can assign arbitrary properties to arrays, they are not considered to be elements of the array and thus ignored by most processes which deal with arrays.

Additionally you might want to have a look at jQuery.param to see how jQuery will convert the input to a transport-able string and adjust your data structure accordingly.

labels['<?php echo $cd['name'] ; ?>'] =

It seems you want to create an associative array, which is in fact an object in JavaScript (JavaScript has no dedicated associative arrays). So the array itself is in fact empty because you are adding properties to the array object.

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