返回到:Prototype – 表单管理
此方法用于将表单数据序列化为适合 Ajax 请求的字符串(默认行为),或者如果可选的 getHash 计算结果为真,则为对象哈希,其中键是表单控件名称,值是数据。
根据可选参数 getHash 的计算结果是否为真,结果要么是 {name: “johnny”, color: “blue”} 形式的对象,要么是 “name = johnny&color = blue” 形式的字符串,适合用于 Ajax 请求中的参数。
语法
formElement.serialize([getHash = false]);
返回值
它返回一个字符串对象。
这里有两个关于它如何工作的提示。有关详细信息,请查看下面的示例。
$('example').serialize()
// 'username = sulien&age = 22&hobbies = coding&hobbies = hiking'
$('example').serialize(true)
// {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}
例子
HTML
x
45
45
1
<html>
2
<head>
3
<title>Prototype examples</title>
4
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
5
6
<script>
7
function showResult() {
8
var form = $('example');
9
var element = form.serialize();
10
alert("form.serialize() : " + element.inspect());
11
}
12
</script>
13
</head>
14
15
<body>
16
<p>Click the button to see the result.</p>
17
<br />
18
19
<form id = "example" action = "#" onsubmit = "return false">
20
<fieldset>
21
<legend>User info</legend>
22
<div>
23
<label for = "username">Username:</label>
24
<input name = "username" id = "username" value = "Sulien" type = "text">
25
</div>
26
<div>
27
<label for = "age">Age:</label>
28
<input name = "age" id = "age" value = "23" size = "3" type = "text">
29
</div>
30
<div>
31
<label for = "hobbies">Your hobbies are:</label>
32
<select name = "hobbies" id = "hobbies" multiple = "multiple">
33
<option>coding</option>
34
<option>swimming</option>
35
<option>hiking</option>
36
<option>drawing</option>
37
</select>
38
</div>
39
</fieldset>
40
</form>
41
<br />
42
43
<input type = "button" value = "Result" onclick = "showResult();"/>
44
</body>
45
</html>
返回到:Prototype – 表单管理
阅读剩余 86%
作者:terry,如若转载,请注明出处:https://www.web176.com/prototype_api/8499.html