【问题标题】:Serializing an array in jQuery在jQuery中序列化一个数组
【发布时间】:2011-05-13 11:20:54
【问题描述】:

如何为$.ajax提交准备一个元素数组?

这里的图片返回["val1","val2"],但在我使用$.param(images) 之后,我得到以下信息:

未定义=未定义&未定义=未定义


这是我的代码:

$('#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 脚本。

【问题讨论】:

    标签: jquery form-submit form-serialize


    【解决方案1】:

    您没有将格式正确的数组传递给$.param。来自jQuery.param docs

    如果传递的对象是Array,则必须是.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;
    });
    

    【讨论】:

    • 这件事对我来说很难理解,但是通过您的回答和一些调查,我已经成功地做到了我想要的,谢谢 =)
    【解决方案2】:

    docs for $.param

    如果传递的对象是Array,则必须是.serializeArray()返回格式的对象数组

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

    这意味着您需要以相同的方式生成数组:

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

    【讨论】:

      【解决方案3】:

      我从另一个问题中找到了一个很棒的功能 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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-18
        • 2017-01-25
        • 2018-09-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 2014-12-05
        相关资源
        最近更新 更多