JavaScript 操作表單(獲取數據及MD5加密)
1 獲取和設置表單的值
實現步驟:
step1: 對應的< input >添加id屬性。
step2: document.getElementById()
step3: .value
測試代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="#" method="post">
<p>
<span>用戶名:</span><input type="text" id = "username">
</p>
</form>
<script>
//獲取用戶名輸入框的值
var input_id = document.getElementById('username');
</script>
</body>
</html>
控制檯中輸入:
input_id.value
//也可以直接賦值進行修改 input_id.value = '123'
測試結果:
2 表單提交驗證及前端密碼MD5加密
此處先展示一個簡易的表單,通過js在控制檯顯示提交的表單值,並截取提交的表單值
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="#" method="post">
<p>
<span>用戶名:</span> <input type="text" id = "username" name="username" required>
</p>
<p>
<span>密碼:</span> <input type="password" id="password" name="password" required>
</p>
<!--綁定事件onclick被點擊-->
<button type="submit" onclick="aaa()">提交</button>
</form>
<script>
function aaa() {
var uname = document.getElementById("username");
var pwd = document.getElementById("password");
console.log(uname.value);
console.log(pwd.value);
}
</script>
</body>
</html>
測試結果:
通過Network抓取數據顯示如下:(重點看Form Data中語句:)
現使用MD5對其加密!
MD5工具類:https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js
使用script導入:<script src = "https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
更改上述代碼中的function如下:(核心語句:pwd.value = md5(pwd.value);
)
function aaa() {
var uname = document.getElementById("username");
var pwd = document.getElementById("password");
console.log(uname.value);
//MD5算法
pwd.value = md5(pwd.value);
console.log(pwd.value);
}
測試結果:
對上述代碼進行優化:
- 對提交功能優化,上述代碼採用button綁定觸發事件,現直接使用表單的
onsubmit=""
進行綁定。 - 在上述代碼提交的瞬間,密碼會變長,這是md5加密的結果。降低用戶體驗,以下代碼中採用
input-password
、md5-password
兩種密碼(一個顯性、一個隱形),可以局部優化! - 以下代碼中利用
onsubmit="return ..."
,並在觸發函數的結尾設置return true/false;
關卡,控制表單是否可以提交。
優化後的代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--MD5工具類-->
<script src = "https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script>
</head>
<body>
<form action="http://www.baidu.com/" method="post" onsubmit="return aaa()">
<p>
<span>用戶名:</span> <input type="text" id = "username" name="username" required>
</p>
<p>
<!--這是用戶輸入的密碼,但是沒有賦name屬性,network無法截獲,起到隱藏的作用-->
<span>密碼:</span> <input type="password" id="input-password">
</p>
<!--此處賦name屬性,會被network截獲,但是截獲的是md5加密後的密碼,實現可關注aaa()中代碼-->
<input type="hidden" id="md5-password" name="password">
<button type="submit">提交</button>
</form>
<script>
function aaa() {
var uname = document.getElementById("username");
var pwd = document.getElementById("input-password");
var md5pwd = document.getElementById("md5-password");
//MD5算法加密
md5pwd.value = md5(pwd.value);
return true;
}
</script>
</body>
</html>
測試結果:
寫在最後
年輕人,
你的職責是平整土地,
而非焦慮時光。
你做三四月的事,
在八九月自有答案。
——《時間之書》
To Demut and Dottie!