Prototype - Form serialize() 方法
此方法用于将表单数据序列化为适合 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 = climbing'
$('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>单击按钮查看结果。</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.html

