-
Notifications
You must be signed in to change notification settings - Fork 27
/
serializeForm.js
64 lines (53 loc) · 1.77 KB
/
serializeForm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* 将一个表单元素序列化为可提交的字符串
*
* @param {FormElement} form 需要序列化的表单元素
* @return {string} 表单序列化后的字符串
*/
function serializeForm(form) {
if (!form || form.nodeName.toUpperCase() !== 'FORM') {
return;
}
var result = [];
var i, len;
var field, fieldName, fieldType;
for (i = 0, len = form.length; i < len; ++i) {
field = form.elements[i];
fieldName = field.name;
fieldType = field.type;
if (field.disabled || !fieldName) {
continue;
} // enf if
switch (fieldType) {
case 'text':
case 'password':
case 'hidden':
case 'textarea':
result.push(encodeURIComponent(fieldName) + '=' +
encodeURIComponent(field.value));
break;
case 'radio':
case 'checkbox':
if (field.checked) {
result.push(encodeURIComponent(fieldName) + '=' +
encodeURIComponent(field.value));
}
break;
case 'select-one':
case 'select-multiple':
for (var j = 0, jLen = field.options.length; j < jLen; ++j) {
if (field.options[j].selected) {
result.push(encodeURIComponent(fieldName) + '=' +
encodeURIComponent(field.options[j].value || field.options[j].text));
}
} // end for
break;
case 'file':
case 'submit':
break; // 是否处理?
default:
break;
} // end switch
} // end for
return result.join('&');
}