Django – 使用JavaScript弹出确认框停止注销

huangapple go评论88阅读模式
英文:

Django - stop logout with javascript pop-up confirm box

问题

以下是您要求的代码部分的中文翻译:

# views.py

def logout(request):
    if "user_info" in request.session:
        del request.session["user_info"]
    # 重定向到登录页面,以便用户可以重新登录
    return redirect("login")
// script.js

function logout_popup() {
    if (confirm("您确定吗?")) {
        window.location.reload();
    }
}
<!-- base.html -->

<li onclick="logout_popup()" id="logout-tab"><a href="{% url 'logout' %}">注销</a></li>
英文:

In my django site I have a logout button that redirects to the view logout. When the button is clicked it instantly logs the user out, but I would like a JS pop-up confirm box to appear then the logout button is clicked.

When the user clicks 'Ok' OR 'Cancel' it logs the user out. How can i prevent the logout view being called when the user clicks 'Cancel'?

views.py

def logout(request):
    if &quot;user_info&quot; in request.session:
        del request.session[&quot;user_info&quot;]
    #redirect to login so the user can log back in
    return redirect(&quot;login&quot;)

script.js

function logout_popup() {
    if (confirm(&quot;Are you sure?&quot;)) {
        window.location.reload()
    }
}

base.html

&lt;li onclick=&quot;logout_popup()&quot; id=&quot;logout-tab&quot;&gt;&lt;a href=&quot;{% url &#39;logout&#39; %}&quot;&gt;Logout&lt;/a&gt;&lt;/li&gt;

答案1

得分: 0

尝试将 onclick 移动到 a 标签:

<li id="logout-tab"><a href="{% url 'logout' %}" onclick="logout_popup(event)">注销</a></li>

以及脚本部分:

function logout_popup(e) {
    if (confirm("确定要注销吗?")) {
        window.location.reload();
    } else {
        e.preventDefault();
    }
}
英文:

Try to move the onclick to the a tag:

&lt;li id=&quot;logout-tab&quot;&gt;&lt;a onclick=&quot;logout_popup(event)&quot; href=&quot;{% url &#39;logout&#39; %}&quot;&gt;Logout&lt;/a&gt;&lt;/li&gt;

and the script:

function logout_popup(e) {
    if (confirm(&quot;Are you sure?&quot;)) {
        window.location.reload()
    } else {
        e.preventDefault()
    }
}

huangapple
  • 本文由 发表于 2023年1月8日 22:38:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定