JavaScript 基础与提高

JavaScript 坑与技巧:表单

2017-02-06  本文已影响87人  soojade

表单

巧用 input 加密提交

很多登录表单出于安全考虑,提交时不传输明文密码,而是密码的MD5。普通JavaScript开发人员会直接修改<input>

<!-- HTML -->
<form id="login-form" method="post" onsubmit="return checkForm()">
    <input type="text" id="username" name="username">
    <input type="password" id="password" name="password">
    <button type="submit">Submit</button>
</form>

<script>
function checkForm() {
    var pwd = document.getElementById('password');
    // 把用户输入的明文变为MD5:
    pwd.value = toMD5(pwd.value);
    // 继续下一步:
    return true;
}
</script>

这个做法看上去没啥问题,但用户输入了密码提交时,密码框的显示会突然从几个*变成32个*(因为MD5有 32 个字符)。

要想不改变用户的输入,可以利用<input type="hidden">实现:

<!-- HTML -->
<form id="login-form" method="post" onsubmit="return checkForm()">
    <input type="text" id="username" name="username">
    <input type="password" id="input-password">
    <input type="hidden" id="md5-password" name="password">
    <button type="submit">Submit</button>
</form>

<script>
function checkForm() {
    var input_pwd = document.getElementById('input-password');
    var md5_pwd = document.getElementById('md5-password');
    // 把用户输入的明文变为MD5:
    md5_pwd.value = toMD5(input_pwd.value);
    // 继续下一步:
    return true;
}
</script>

注意到idmd5-password<input>标记了name="password",而用户输入的idinput-password<input>没有name属性。没有name属性的<input>的数据不会被提交。

上一篇下一篇

猜你喜欢

热点阅读