返回值:ArrayserializeArray()

把表单元素编码成一个键/值对的数组。

.serializeArray() 方法会创建一个 JavaScript 对象数组,可以用于编码成 JSON 字符串。它可以对一个代表一组表单元素的 jQuery 对象进行操作。表单元素可以有以下几种类型:

<form>
  <div><input type="text" name="a" value="1" id="a" /></div>
  <div><input type="text" name="b" value="2" id="b" /></div>
  <div><input type="hidden" name="c" value="3" id="c" /></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
  </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f" />
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g" />
  </div>
</form>

.serializeArray() 方法使用了 W3C 关于 successful controls (有效控件) 的标准来检测哪些元素应当包括在内。被禁用的元素不会被包括在内。并且,元素必须含有 name 属性。此外,提交按钮的值也不会被序列化。文件选择元素的数据也不会被序列化。

.serializeArray() 方法可以对单独选择的表单元素对象进行操作,比如 <input>, <textarea>, 和 <select>。然而,还有个更方便的方法是,直接使用 <form> 标签来进行序列化操作:

$('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});

于是,就生成了如下的数据结构: (该结果由支持 console.log 方法的浏览器输出):

[
  {
    name: "a",
    value: "1"
  },
  {
    name: "b",
    value: "2"
  },
  {
    name: "c",
    value: "3"
  },
  {
    name: "d",
    value: "4"
  },
  {
    name: "e",
    value: "5"
  }
]

示例:

从一个表单中获取数据,并显示每个被选中的控件的值。

<!DOCTYPE html>
<html>
<head>
<style>
  body, select { font-size:14px; }
  form { margin:5px; }
  p { color:red; margin:5px; }
  b { color:blue; }
  </style>
<script src="jquery.min.js"></script>
</head>
<body>

<p><b>Results:</b> <span id="results"></span></p>

  <form>
    <select name="single">
      <option>Single</option>
      <option>Single2</option>

    </select>
    <select name="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>

      <option selected="selected">Multiple3</option>
    </select><br/>
    <input type="checkbox" name="check" value="check1" id="ch1"/>

    <label for="ch1">check1</label>
    <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>

    <label for="ch2">check2</label>
    <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>

    <label for="r1">radio1</label>
    <input type="radio" name="radio" value="radio2" id="r2"/>

    <label for="r2">radio2</label>
  </form>

<script>



    function showValues() {
      var fields = $(":input").serializeArray();
      $("#results").empty();
      jQuery.each(fields, function(i, field){
        $("#results").append(field.value + " ");
      });
    }

    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();


</script>
</body>
</html>

演示: