ドキュメント

Ajax/serializeArray

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Ajax

serializeArray( )

Serializes all forms and form elements (like the .serialize() method) but returns a JSON data structure for you to work with.
Note: The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify".
The returned JSON structure consists of an Array of Objects where each Object contains one or two keys: name for the parameter name and value for the parameter value if set/not empty.

Example:

  [ 
     {name: 'firstname', value: 'Hello'}, 
     {name: 'lastname', value: 'World'},
     {name: 'alias'}, // this one was empty
  ]

Note that serializeArray() only works on form elements, using this method on another element will not work. Also, this method will not give any results on nested forms, which are illegal in HTML anyway.
Examples:

Get the values from a form, iterate through them, and append them to a results display.

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    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>
  <style>
  body, select { font-size:14px; }
  form { margin:5px; }
  p { color:red; margin:5px; }
  b { color:blue; }
  </style>
</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>
</body>
</html>

NameType