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

Python+Flask项目:加载按钮与后端函数调用实现问询

Solution for Your "Update Product" Button with Loading State & Backend Integration

Got it, let's build this out step by step for your school project! I'll break this down into frontend (HTML/CSS/jQuery) and backend (Flask) components that play nicely with your tech stack.

1. HTML Structure

First, we'll create two buttons: your original "Update Product" button, and a loading-state button hidden by default. We'll use Bootstrap classes for consistent styling:

<!-- Original Update Button -->
<button id="updateBtn" class="btn btn-primary">Update Product</button>

<!-- Loading Button (Hidden Initially) -->
<button id="loadingBtn" class="btn btn-primary" disabled style="display: none;">
  <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
  Updating...
</button>

<!-- Message Area for Status Feedback -->
<div id="statusMessage" class="mt-3"></div>

2. CSS for Loading Button

We'll add a touch of custom CSS to polish the loading button (no external links needed—this matches the behavior you referenced):

/* Optional: Fine-tune spinner spacing */
.spinner-border {
  margin-right: 0.5rem;
}

3. jQuery/JavaScript Logic

This is where we handle the button click, toggle states, and make the AJAX call to your Flask backend. We'll use jQuery since it's part of your allowed tech stack:

$(document).ready(function() {
  $('#updateBtn').click(function() {
    // Hide original button, show loading state
    $('#updateBtn').hide();
    $('#loadingBtn').show();
    $('#statusMessage').text('').removeClass('alert alert-success alert-danger');

    // Make AJAX call to Flask backend
    $.ajax({
      url: '/update-products',  // Match your Flask route
      type: 'POST',
      dataType: 'json',
      success: function(response) {
        // Handle backend response
        if (response.status === 'ok') {
          $('#statusMessage').text('Products updated successfully!').addClass('alert alert-success');
        } else if (response.status === 'ko') {
          $('#statusMessage').text('Failed to update products. Please try again.').addClass('alert alert-danger');
        }
        // Reset buttons after processing
        resetButtons();
      },
      error: function() {
        // Handle network/backend errors
        $('#statusMessage').text('An error occurred. Please check your connection.').addClass('alert alert-danger');
        resetButtons();
      }
    });
  });

  // Helper function to reset button states
  function resetButtons() {
    $('#loadingBtn').hide();
    $('#updateBtn').show();
  }
});

4. Flask Backend Implementation

Now let's create the Flask route that runs your updateProducts() function and returns the status. I'll include a simulated delay to mimic real processing time:

from flask import Flask, jsonify

app = Flask(__name__)

def updateProducts():
    # Replace this with your actual product update logic
    # For demo, we'll simulate processing time and random status
    import time
    time.sleep(2)  # Simulate database/API calls
    # Replace the line below with your actual success/failure check
    return 'ok'  # or 'ko' based on your logic

@app.route('/update-products', methods=['POST'])
def handle_update_products():
    try:
        status = updateProducts()
        return jsonify({'status': status})
    except Exception as e:
        # Log error for debugging (optional)
        print(f"Update error: {e}")
        return jsonify({'status': 'ko'}), 500

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

Quick Notes

  • Make sure you've included jQuery and Bootstrap CSS/JS in your template (via CDN or local files) for styling and AJAX functionality.
  • Adjust the /update-products route URL to match your Flask app's routing structure.
  • Replace the simulated logic in updateProducts() with your actual product update code (e.g., database operations, API calls).

内容的提问来源于stack exchange,提问作者L.P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:21:40