Prototype - 表单序列化方法



此方法用于将表单数据序列化为适合 Ajax 请求(默认行为)的字符串,或者如果可选参数 getHash 评估为 true,则序列化为一个对象散列,其中键是表单控件名称,值是数据。

根据可选参数 getHash 是否评估为 true,结果将是 {name: "johnny", color: "blue"} 形式的对象或 "name = johnny&color = blue" 形式的字符串,适合 Ajax 请求中的参数。

语法

formElement.serialize([getHash = false]);

返回值

它返回一个 String 对象。

下面是两个关于它的工作原理的提示。请详细查看下面的示例。

$('example').serialize()
// 'username = sulien&age = 22&hobbies = coding&hobbies = hiking'
$('example').serialize(true)
// {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}

示例

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var form = $('example'); 
            var element = form.serialize(); 
            alert("form.serialize() : " + element.inspect());
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />

      <form id = "example" action = "#" onsubmit = "return false">
         <fieldset>
            <legend>User info</legend>
            <div>
               <label for = "username">Username:</label> 
               <input name = "username" id = "username" value = "Sulien" type = "text">
            </div>
            <div>
               <label for = "age">Age:</label> 
               <input name = "age" id = "age" value = "23" size = "3" type = "text">
            </div>
            <div>
               <label for = "hobbies">Your hobbies are:</label>
               <select name = "hobbies" id = "hobbies" multiple = "multiple">
                  <option>coding</option>
                  <option>swimming</option>
                  <option>hiking</option>
                  <option>drawing</option>
               </select>
            </div>
         </fieldset>
      </form>
      <br />
      
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>

输出

prototype_form_management.htm
广告