首页 > 解决方案 > 如果提交正确,如何禁用 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")

标签: javascriptflaskdom-events

解决方案


由于 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'] 的值更改为您希望用户在重定向后看到的值,然后将用户重定向到想要的位置。


推荐阅读