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

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

Django - stop logout with javascript pop-up confirm box

问题

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

  1. # views.py
  2. def logout(request):
  3. if "user_info" in request.session:
  4. del request.session["user_info"]
  5. # 重定向到登录页面,以便用户可以重新登录
  6. return redirect("login")
  1. // script.js
  2. function logout_popup() {
  3. if (confirm("您确定吗?")) {
  4. window.location.reload();
  5. }
  6. }
  1. <!-- base.html -->
  2. <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

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

script.js

  1. function logout_popup() {
  2. if (confirm(&quot;Are you sure?&quot;)) {
  3. window.location.reload()
  4. }
  5. }

base.html

  1. &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 标签:

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

以及脚本部分:

  1. function logout_popup(e) {
  2. if (confirm("确定要注销吗?")) {
  3. window.location.reload();
  4. } else {
  5. e.preventDefault();
  6. }
  7. }
英文:

Try to move the onclick to the a tag:

  1. &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:

  1. function logout_popup(e) {
  2. if (confirm(&quot;Are you sure?&quot;)) {
  3. window.location.reload()
  4. } else {
  5. e.preventDefault()
  6. }
  7. }

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:

确定