javascript - 如果提交正确,如何禁用 event.preventDefault()?
问题描述
我想重定向到主页并使用flask闪烁一条消息,我想我需要禁用该preventDefault()
功能:
login_form.addEventListener("submit", (event) => {
event.preventDefault();
axios.post(login_form.action, {
username: login_form.username.value,
password: login_form.pass.value
}).then((response) => {
if (response.data["returnval"] === "wrong-crd")
{
_alert.innerHTML = "Username or password is incorrect";
_alert.hidden = false;
}
else
{
window.location.href = "/";
}
});
});
该代码有效,但我无法闪烁消息,如何禁用该preventDefault()
功能。
我的烧瓶代码:
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "GET":
return render_template("login.html")
else:
username = request.json.get("username")
password = request.json.get("password")
cursor.execute("SELECT * FROM Users WHERE username = %s", (username,))
returned = cursor.fetchall()
if len(returned) == 0:
return jsonify(returnval="wrong-crd")
if check_password_hash(returned[0][3], password):
session.permanent = True
session["userId"] = returned[0][0]
flash("Logged in!")
return redirect("/")
else:
return jsonify(returnval="wrong-crd")
解决方案
由于 AJAX 是异步的,这意味着在您提交请求后获得响应需要时间。
如果您在开始时不阻止默认事件,它通常会在您收到响应之前触发该默认事件。
你可以这样做:
制作一个会弹出消息的函数,如下所示:
function pushNotification(message){
alert(message);
}
我们将使用localStorage来存储需要显示的弹出消息。因此,首先我们将在您的主 javascript 文件中添加一个小代码,该代码将触发我们刚刚创建的函数:
let nextMSG = localStorage['nextMessage'];
if(nextMSG!=undefined && nextMSG!=""){
pushNotification(nextMSG);
localStorage['nextMessage']="";
}
现在您所要做的就是修改您的代码,以便:
a) - 当响应失败时(用户没有登录),你pushNotification()
直接调用函数
b) - 当用户登录时,您首先将 localStorage['nextMessage'] 的值更改为您希望用户在重定向后看到的值,然后将用户重定向到想要的位置。
推荐阅读
- python - 如何将 4 维 PyTorch 张量乘以 1 维张量?
- spring-kafka - Kafka Listener 上的千分尺定时注释
- python - 从 SQLAlchemy declarative_base 定义的表中选择
- jestjs - Jest-Puppeteer 为什么警告“测试运行完成后一秒钟 Jest 没有退出
- sql - 在oracle sql中使用plsql检查表中是否存在两个值
- symfony - Symfony Omines 数据表列选项“过滤器”
- javascript - 使用 Javascript 的弹跳动画?
- powershell - PowerShell 将变量输出添加到正则表达式组
- prolog - prolog 中复制的实现
- javascript - 如何根据javascript中另一个随机变量的结果来调节随机生成器中的字符串变量?