2010-11-21 48 views
11

如何为$.ajax提交此阵列? 这里图像返回["val1","val2"]但我用$.param(images)后我回来undefined=undefined&undefined=undefined在Jquery中序列化数组?

$('#rem_images').click(function(){ 
     var images = new Array(); 
     $('.images_set_image input:checked').each(function(i){ 
      images[i] = $(this).val(); 
     }); 
     alert($.param(images)); 
     return false; 

一般的想法是检查图像删除网页然后按一下按钮环槽的所有图像检查和序列化阵列AJAX提交到PHP脚本。

回答

23

您没有以适当的格式将数组传递给$.param。从jQuery.param docs

如果传递的目的是在一个数组,它必须是物体在由.serializeArray()返回的格式的阵列。

该数组应该是由名称/值对组成的对象数组。您看到undefined=undefined&undefined=undefined,因为"val1".name"val1".value,"val2".name"val2".value都未定义。它应该是这个样子:

[{name: 'name1', value: 'val1'}, {name: 'name2', value: 'val2'}] 

所以,你可以构建这样的阵列(假设你的复选框具有name属性):

$('#rem_images').click(function(){ 
    var images = []; 
    $('.images_set_image input:checked').each(function(){ 
     var $this = $(this); 
     images.push({name: $this.attr('name'), value: $this.val()}); 
    }); 
    alert($.param(images)); 
    return false; 
}); 

即使雨衣,虽然是使用.map()(因为函数式编程是好东西):

$('#rem_images').click(function(){ 
    var images = $('.images_set_image input:checked').map(function(){ 
     var $this = $(this); 
     return {name: $this.attr('name'), value: $this.val()}; 
    }).get(); 
    alert($.param(images)); 
    return false; 
}); 
+1

这件事情是我很难理解,但你的答案和一些调查,我能够做到我想要什么,谢谢你=) – Metafaniel 2012-06-15 19:58:10

7

docs for $.param

如果传递的对象是一个Array,它必须是物体在这意味着你需要生成同样的方式排列()

[{name:"first",value:"Rick"}, 
{name:"last",value:"Astley"}, 
{name:"job",value:"Rock Star"}] 

由.serializeArray返回的格式的数组:

$('.images_set_image input:checked').each(function(i){ 
    images.push({ name: i, value: $(this).val() }); 
}); 
+0

你的回答对我也有帮助,非常感谢=) – Metafaniel 2012-06-15 19:58:31

0

我找到一个伟大的功能,要做到这一点从另一个问题 https://stackoverflow.com/a/31751351/4110122

与键值对这个函数的返回数组

$.fn.serializeObject = function() { 
    var o = {}; 
    var a = this.serializeArray(); 
    $.each(a, function() { 
     if (o[this.name] !== undefined) { 
      if (!o[this.name].push) { 
       o[this.name] = [o[this.name]]; 
      }  
      o[this.name].push(this.value || ''); 
     } else { 
      o[this.name] = this.value || ''; 
     } 
    }); 
    return o; 
}; 

要使用此只要致电:

var Form_Data = $('form').serializeObject(); 
console.log(Form_Data);