You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python登录页如何对接JS实现错误密码弹窗提示?

Hey there! Let's get that SweetAlert popping up when login fails. The key here is to connect your frontend (JS) with your backend (Python) using an asynchronous request—this way you can handle the response without reloading the page, and trigger the popup directly from your JS. Here's how to do it step by step:

Step 1: Update Your HTML Login Form

First, add IDs to your inputs and login button so JS can easily grab their values, and make sure you have username/password fields (I assume you have them but didn't include them in your snippet):

<div>
  <input type="text" id="username" placeholder="Enter username">
  <input type="password" id="password" placeholder="Enter password">
  <button id="loginBtn">Login</button>
</div>
Step 2: Wrap Your SweetAlert in a Reusable Function

Turn your existing popup code into a function so you can call it whenever login fails:

function showLoginError() {
  let timerInterval
  Swal.fire({
    title: 'You entered wrong username or password',
    html: 'I will close in <b></b> milliseconds.',
    timer: 2000,
    timerProgressBar: true,
    onBeforeOpen: () => {
      Swal.showLoading()
      timerInterval = setInterval(() => {
        const content = Swal.getContent()
        if (content) {
          const b = content.querySelector('b')
          if (b) {
            b.textContent = Swal.getTimerLeft()
          }
        }
      }, 100)
    },
    onClose: () => {
      clearInterval(timerInterval)
    }
  }).then((result) => {
    if (result.dismiss === Swal.DismissReason.timer) {
      console.log('I was closed by the timer')
    }
  })
}
Step 3: Add an Async Login Handler with Fetch

Use JavaScript's fetch API to send login data to your backend without reloading the page, then handle the response:

document.getElementById('loginBtn').addEventListener('click', async () => {
  // Grab user input values
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  try {
    // Send POST request to your backend login endpoint
    const response = await fetch('/login', { // Replace '/login' with your actual backend route
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });

    // Get the response from your backend
    const responseText = await response.text();

    // Handle success/failure
    if (responseText === 'Successful') {
      // Do something on login success (e.g., redirect to dashboard)
      window.location.href = '/dashboard';
    } else if (responseText === 'invalid credentials') {
      // Trigger your error popup!
      showLoginError();
    }
  } catch (error) {
    console.error('Login request failed:', error);
    // Optional: Show a network error popup
    Swal.fire('Oops!', 'Failed to connect to the server.', 'error');
  }
});

Returning JSON instead of plain text makes your responses more flexible (you can add extra data later like user IDs or tokens). Here's how to adjust your Python code (example using Flask):

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    # Get username and password from the frontend request
    login_data = request.get_json()
    username = login_data.get('username')
    password = login_data.get('password')

    # Your existing login validation logic here
    login_result = '0' if (username == 'valid_user' and password == 'valid_pass') else '1'

    if login_result == '0':
        return jsonify({'status': 'success', 'message': 'Successful'})
    else:
        return jsonify({'status': 'error', 'message': 'invalid credentials'})

if __name__ == '__main__':
    app.run(debug=True)

If you use JSON responses, update your JS fetch handler to parse JSON instead of text:

const responseData = await response.json();
if (responseData.status === 'success') {
  window.location.href = '/dashboard';
} else {
  showLoginError();
}

That's it! Now when your backend returns an error, your JS will catch it and trigger the SweetAlert popup exactly as you want.

内容的提问来源于stack exchange,提问作者CodeGirl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:58:11