简体   繁体   English

通过Ajax发送数组失败

[英]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? 为什么我不能像这样发送labels数组? It doesn't show anything in Firebug. 它没有在Firebug中显示任何内容。

My console.log(labels) result: 我的console.log(labels)结果:

[]

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. JavaScript中的数组只能使用数字键来保存元素。 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. 另外,您可能需要查看jQuery.param以了解jQuery如何将输入转换为可传输字符串并相应地调整数据结构。

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). 看起来你想创建一个关联数组,它实际上是JavaScript中的一个对象(JavaScript没有专用的关联数组)。 So the array itself is in fact empty because you are adding properties to the array object. 因此,数组本身实际上是空的,因为您要向数组对象添加属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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