【问题标题】:Multidimensional array not being POSTed未发布多维数组
【发布时间】:2014-03-05 16:33:49
【问题描述】:

我正在构建一个多维数组并尝试通过 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,但文件数组不是。

什么给了?

【问题讨论】:

  • 文件列表在什么范围内?贴出更完整的代码
  • 不确定是否有区别,但为什么fileinfo 是一个数组而不是一个对象?
  • 好吧,我正在用 PHP 获取数据(准确地说是 CodeIgniter)。我会尝试将 filelist 作为对象,但这能解决问题吗?
  • 您确定 .each 发生在 ajax 调用之前吗?

标签: javascript jquery arrays multidimensional-array


【解决方案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

【讨论】:

  • 这行得通,但为什么呢?为什么数组数组不起作用,为什么包含数组的对象会失败?只有一组对象起作用......非常奇怪!
  • 这可以解释它:jsfiddle.net/TwoToneBytes/K2pXw/1。基本上,由于您实际上并没有向数组推送任何内容,因此它的长度不会更新。所以 JSON.stringify 返回一个空数组。
【解决方案2】:

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

例如

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 让在服务器端发布和处理发布的数据变得更加轻松。

【讨论】:

    猜你喜欢
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2010-12-15
    • 2011-01-03
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多