跳到主要内容

serialize 方案

提示

本篇文章我们分写介绍了使用jQuery中的**serialize()实现表单序列化和使用手写的serialize()**实现表单序列化

手写 serialize() 实现表单序列化


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ajax</title>
</head>
<body>
<form id="form">
<div>
<label for="username">用户名:</label>
<input type="text" name="username" />
</div>
<div>
<label for="password">密码:</label>
<input type="password" name="password" />
</div>
<div>
<button id="btn">发送</button>
</div>
</form>
<script>
function serialize(form) {
const result = [];
const { elements } = form;
for (let i = 0; i < elements.length; i++) {
let formItem = elements[i];
if (formItem.disabled) continue;
switch (formItem.type) {
case "file":
case "submit":
case "button":
case "image":
case "reset":
case undefined:
break;
case "select-one":
case "select-multiple":
if (formItem.name && formItem.name.length) {
const { options } = formItem;
for (let j = 0; j < options.length; j++) {
option = options[j];
let value = "";
if (option.selected) {
if (option.hasAttribute) {
value = option.hasAttribute("value")
? option.value
: option.text;
} else {
value = option.attributes("value").specified
? option.value
: option.text;
}
result.push(
encodeURIComponent(formItem.name) +
"=" +
encodeURIComponent(value)
);
}
}
}
break;
case "radio":
case "checkbox":
if (!formItem.checked) break;
default:
if (formItem.name && formItem.name.length) {
result.push(
encodeURIComponent(formItem.name) +
"=" +
encodeURIComponent(formItem.value)
);
}
}
}
return result.join("&");
}
const btn = document.getElementById("btn");
btn.addEventListener("click", function (e) {
e.preventDefault();
const form = document.getElementById("form");
const params = serialize(form);
console.log(params);
});
</script>
</body>
</html>

jQuery serialize() 实现表单序列化


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>jQuery serialize() 表单序列化</title>
</head>
<body>
<form id="form">
<div>
<label for="username">用户名:</label>
<input type="text" name="username" />
</div>
<div>
<label for="password">密码:</label>
<input type="password" name="password" />
</div>
<div>
<button id="btn">发送</button>
</div>
</form>
<script>
const btn = document.getElementById("btn");
btn.addEventListener("click", function (e) {
e.preventDefault();
const form = document.getElementById("form");
const params = $("form").serialize();
console.log(params);
});
</script>
</body>
</html>

参考资料


前端扫地僧-原生js书写jquery中的serialize用法