52

我在序列化表单时遇到了一些麻烦

<form>
    <input type="text" name="name1" value="value1"/>
    <input type="text" name="name2" value="value2"/>
</form>

$(form).serializeArray()

将返回[{name:"name1",value:"value1"},{name:"name2",value:"value2"}]对。

是否有可能以表格形式获得输出

{name1:value1,name2:value2}

让他们更容易处理?

4

11 回答 11

89
var result = { };
$.each($('form').serializeArray(), function() {
    result[this.name] = this.value;
});

// at this stage the result object will look as expected so you could use it
alert('name1 = ' + result.name1 + ', name2 = ' + result.name2);

现场演示。

于 2012-07-07T15:24:04.560 回答
39
$.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;
};
于 2015-07-31T16:54:42.940 回答
29

如果您的表单没有复选框或单选按钮,则接受的答案非常有用。由于这些组都具有相同的名称属性,因此您需要在对象内创建一个数组值。所以对于像这样的html:

<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="2" name="the-checkbox">
<input type="checkbox" value="3" name="the-checkbox">

你会得到:

{the-checkbox:['1', '2', '3']}

这段代码可以很好地处理所有事情。

/*!
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.

(function($,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  $.fn.serializeObject = function(){
    var obj = {};
    
    $.each( this.serializeArray(), function(i,o){
      var n = o.name,
        v = o.value;
        
        obj[n] = obj[n] === undefined ? v
          : $.isArray( obj[n] ) ? obj[n].concat( v )
          : [ obj[n], v ];
    });
    
    return obj;
  };
  
})(jQuery);

用法

$(form).serializeObject();
于 2012-09-13T03:42:58.500 回答
7
new_obj = {}

$.each($(form).serializeArray(), function(i, obj) { new_obj[obj.name] = obj.value })

您的数据在 new_obj 中

于 2012-07-07T15:27:02.793 回答
4

您可以非常简单地使用.reduce()和解构赋值:

const arr = $('form').serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object

例子:

$('form').on('submit', function(e) {
  e.preventDefault(); // only used for example (so you can see output in console);
  const arr = $(this).serializeArray(); // get the array
  const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" placeholder="username" name="username"/>
  <input type="email" placeholder="email" name="email"/>
  <input type="submit" />
</form>

或者如果你能支持它,Object.fromEntries()甚至更容易:.map()

例子:

$('form').on('submit', function(e) {
  e.preventDefault(); // only used for example (so you can see output in console);
  const arr = $(this).serializeArray(); // get the array
  const data = Object.fromEntries(arr.map(({name, value}) => [name, value]));
  console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" placeholder="username" name="username"/>
  <input type="email" placeholder="email" name="email"/>
  <input type="submit" />
</form>

于 2019-06-20T14:56:49.257 回答
3

您可以制作自定义功能。

var complex = $(form).serialize(); // name1=value1&name2=value2
var json = toSimpleJson(complex); // {"name1":"value1", "name2":"value2"}

function toSimpleJson(serializedData) {
    var ar1 = serializedData.split("&");
    var json = "{";
    for (var i = 0; i<ar1.length; i++) {
        var ar2 = ar1[i].split("=");
        json += i > 0 ? ", " : "";
        json += "\"" + ar2[0] + "\" : ";
        json += "\"" + (ar2.length < 2 ? "" : ar2[1]) + "\"";
    }
    json += "}";
    return json;
}
于 2016-10-21T19:47:03.777 回答
2

这是Hollister代码的一些现代化。

(function($,undefined){
  '$:nomunge'; // Used by YUI compressor.

  $.fn.serializeObject = function(){
    var obj = {},
        names = {};

    $.each( this.serializeArray(), function(i,o){
      var n = o.name,
        v = o.value;

        if ( n.includes( '[]' ) ) {
          names.n = !names.n ? 1 : names.n+1;
          var indx = names.n - 1;
          n = n.replace( '[]', '[' + indx + ']' );
        }

        obj[n] = obj[n] === undefined ? v
          : $.isArray( obj[n] ) ? obj[n].concat( v )
          : [ obj[n], v ];
    });

    return obj;
  };

})(jQuery);

如果您需要myvar[]复选框的字段名称。

于 2016-10-07T14:41:51.757 回答
1

这是我的解决方案,它支持单选按钮和多选。

var data = $('#my_form').serializeArray().reduce(function (newData, item) {
    // Treat Arrays
    if (item.name.substring(item.name.length - 2) === '[]') {
        var key = item.name.substring(0, item.name.length);
        if(typeof(newData[key]) === 'undefined') {
            newData[key] = [];
        }
        newData[key].push(item.value);
    } else {
        newData[item.name] = item.value;
    }
    return newData;
}, {});

console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="my_form">
  <select name="muli_select[]" multiple="multiple">
    <option value="1" selected>Value 1</option>
    <option value="2" selected>Value 2</option>
    <option value="3">Value 3 Not selected</option>
  </select>
  <br>
  <input name="my_text" type="hidden" value="Hidden Text"/>
  <input name="my_text2" type="text" value="Shown Text"/>
  <br>
  
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female
</form>

于 2018-09-28T07:54:58.227 回答
0

给你的表单一个 id(form-id)

var jsoNform = $("#form-id").serializeObject();

jQuery.fn.serializeObject = function () {
    var formData = {};
    var formArray = this.serializeArray();
    for (var i = 0, n = formArray.length; i < n; ++i)
         formData[formArray[i].name] = formArray[i].value;
     return formData;
};
于 2017-11-30T17:20:07.950 回答
0

要仅获取具有值的表单输入...

var criteria = $(this).find('input, select').filter(function () {
    return ((!!this.value) && (!!this.name));
}).serializeArray();

条件:{名称:“姓氏”,值:“史密斯”}

于 2018-06-05T21:50:49.510 回答
0

我还将使用 Nick Parsons 的剪辑添加一些内容:

(function($,undefined){
    $.fn.serializeObject = function(){
        return this.serializeArray()
            .reduce((acc, {name, value}) => ({...acc, [name]: value}),{});
    };

})(jQuery);

其他示例不允许覆盖具有相同名称的字段。“serializeArray” 负责这一点,尼克的剪断使它工作得更好。

于 2021-02-03T12:22:03.870 回答