jQuery serializeArray()键值对

时间:2012-07-07 15:19:36

标签: jquery serialization

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

<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}

这样他们更容易处理?

11 个答案:

答案 0 :(得分:59)

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);

Live demo.

答案 1 :(得分:35)

$.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;
};

答案 2 :(得分:23)

如果您的表单没有复选框或单选按钮,则接受的答案效果很好。由于这些组的所有组都具有相同的name属性,因此您需要在对象内创建一个数组值。所以对于html来说:

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

你会得到:

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

This代码可以很好地处理所有内容。

/*!
 * 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();

答案 3 :(得分:4)

new_obj = {}

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

您的数据位于new_obj

答案 4 :(得分: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;
}

答案 5 :(得分:2)

以下是Hollister代码的一些现代化。

True

如果您需要字段名称(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); 作为复选框。

答案 6 :(得分: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;
};

答案 7 :(得分:0)

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

select name
from sys.objects so
where so.type_desc = 'rule'

标准:{name:“LastName”,值:“smith”}

答案 8 :(得分:0)

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

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>

答案 9 :(得分:0)

您可以使用.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>

答案 10 :(得分:0)

我也会使用 Nick Parsons 的剪辑添加一些内容:

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

})(jQuery);

其他示例不允许覆盖同名字段。 "serializeArray" 解决了这个问题,Nick 的剪辑使它工作得更好。