多维数组未被POST

时间:2014-03-05 16:33:49

标签: javascript jquery arrays multidimensional-array

我正在构建一个多维数组,并试图通过ajax与其他数据位发送它。

以下是我的数组的创建方式:

var filelist = new Array;

    $(this).find('input[name=filename]').each(function(index) {
        var fileinfo = new Array;
        fileinfo['src'] = $(this).data('src');        
        fileinfo['name'] = $(this).val(); 
        filelist.push(fileinfo);
    });

如果我将此回显给控制台,它看起来是正确的。

然后是AJAX电话:

$.ajax({
        type: 'post',
        url: 'my_url_here',
        data: { id: id, files: filelist },
    })

使用Chrome Inspector,我可以看到在表单数据部分传递的ID,但文件数组不是。

是什么给出了?

2 个答案:

答案 0 :(得分:1)

如果您为代码及其周围的范围添加了更多上下文,这可能会有所帮助。

您使用filelist的方式不是数组。为什么不使用传统物体?

var filelist = [];

 $(this).find('input[name=filename]').each(function(index) {
     var fileinfo = {};
     fileinfo.src = $(this).data('src');        
     fileinfo.name = $(this).val(); 
     filelist.push(fileinfo);
 });

你可以看到它在这里工作: http://jsfiddle.net/TwoToneBytes/hMs3y/

它未能按预期工作的原因是由于您只是在数组上设置srcname属性。当jQuery将数组转换为字符串时,它只是一个空数组,因为实际上没有添加任何内容。

var anArray = [];
anArray['foo'] = 'bar';
anArray['bar'] = 'foo';


console.log(anArray.length); // == 0 due to array abuse
console.log(JSON.stringify(anArray)); // returns [] because JSON.stringify is doing for(i<anArray.length) which is 0

答案 1 :(得分:0)

Json是做这类事情的优雅方式:

e.g

Array

( [1] => Array ( [product_id] => 1 [product_model] => HFJ5G1.5 [product_type] => plat [product_return] => graviteits

    )

[2] => Array
    (
        [product_id] => 2
        [product_model] => HHJ5S2.5
        [product_type] => holle plunjer
        [product_return] => veer       

    )
);

可以使用

将其编码为json
json_encode($array);

json看起来像:

{"1":{"product_id":"1","product_model":"HFJ5G1.5","product_type":"plat","product_return":"graviteits"},"2":{"product_id":"2","product_model":"HHJ5S2.5","product_type":"holle plunjer","product_return":"veer"}}

Json使得在服务器端发布和处理发布的数据变得更加轻松。

相关问题