javascript - 承诺并提交
问题描述
我正在构建一个带有前端密码散列的表单:
<form action='login.php' method='post' onsubmit='hash(this)'>
Password: <input type='password' name='password'><br>
<input type='hidden' name='shapassword'>
<input type='submit'>
</form>
我的哈希函数使用 SubtleCrypto Web API。它调用digest()
函数,该函数返回一个 Promise:
function hash(form) {
const buff = new TextEncoder().encode(form.password.value);
p1 = crypto.subtle.digest('SHA-512', buff).then(param => {
form.shapassword.value = new TextDecoder().decode(param);
});
}
但是,shapassword 不会传递给从表单接收数据的脚本。我想hash()
在 Promise 完成之前返回,对吗?如何防止离开hash()
函数或从函数访问form
对象then
?
解决方案
您应该调用preventDefault
以防止用户单击提交表单,并在实际提交表单之前等待Promise
解决。使用 Javascript 而不是内联处理程序附加侦听器也是一种好习惯:
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
getEncodedText(form);
});
function do(form) {
const buff = new TextEncoder().encode(form.password.value);
crypto.subtle.digest('SHA-512', buff).then(param => {
form.shapassword.value = new TextDecoder().decode(param);
form.submit();
});
}
推荐阅读
- python - 在 pyqt5 的 btn.clicked.connect() 方法中返回一个变量
- android - Dagger 组件:错误:找不到符号 kotlin 类
- regex - 正则表达式匹配 - 仅当 4 个字符长且不包含特定单词时
- filebeat - filebeat中多行字符串的正则表达式
- reactjs - dotenv : 如何设置自定义路径
- python - 如何使用来自不同发行者的 jwt?
- javascript - 谷歌折线图 - 未知线问题
- vue.js - nuxt js中未定义窗口
- linux - Get expect 取一个带有空格的变量
- javascript - 道具数据未呈现