use more than a array in jquery post and get php result
我想用jquery将许多数组发布到php页面并获取结果,但是我无法在php页面中给出数组
Notice: Undefined index: $name
Notice: Undefined index: $type
Notice: Undefined index: $value
Notice: Undefined index: $size
jquery代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | $('#ss').live('click', function () { $("#main_login").html("<center>waiting plaese . . . .</center>"); var name = []; var type = []; var size = []; var value = []; $(".name").each(function() { name.push($(this).val()); }); $(".type").each(function() { type.push($(this).val()); }); $(".size").each(function() { size.push($(this).val()); }); $(".value").each(function() { value.push($(this).val()); }); $.ajax({ type: 'POST', url: 'process.php', data:"name[]="+name+"&type[]="+type+"&size[]="+size+"&value[]="+value, success: function (data) { $('#main_login').html(data); } }); |
html代码
1 2 3 4 5 6 | <input type="text" class="name" name="name[]" value="" /> <input type="text" class="value" name="value[]" value="" /> <input type="text" class="type" name="type[]" value="" /> <input type="text" class="size" name="size[]" value="" /> send |
php代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $name = $_POST['name']; $size = $_POST['size']; $value = $_POST['value']; $type = $_POST['type']; $names = array( 'name' => '$name', 'size' => '$size', 'value' => '$value', 'type' => '$type', ); foreach( $names as $key => $n ) { echo" The name is".$name[$key]." The size is".$size[$key]." The type is".$type[$key]." The value is".$value[$key]." "; } |
在JavaScript部分中,ajax调用中的这一行是有问题的:
1 | data:"name[]="+name+"&type[]="+type+"&size[]="+size+"&value[]="+value, |
您正在串联数组,这些数组将转换为逗号分隔的字符串。这不是您想要的(考虑已经有逗号的单个值)。而是使用对象符号。 jQuery将处理它:
1 2 3 4 5 6 | data: { name: name, type: type, size: size, value: value } |
第二,在PHP中,此代码有问题:
1 2 3 4 5 6 |
$ name周围的单引号会使它成为$ name的文字字符串(不是变量,而是带有$ ...的文字)。
但是,除此之外,上面的关联数组$ names并没有真正帮助您。我只需要删除整个语句,然后像这样继续操作(注意$ name为单数形式):
1 2 3 4 5 6 7 8 | foreach( $name as $key => $n ) { echo" The name is".$name[$key]." The size is".$size[$key]." The type is".$type[$key]." The value is".$value[$key]." "; } |