Flask and Frontend Interaction: AJAX Requests and JSON Responses

In web development, the front-end and back-end separation is a common architectural pattern. The front-end is responsible for the user interface and interaction, while the back-end handles data processing and business logic. Flask, as a lightweight Python web framework, can easily interact with the front-end. Among them, AJAX (Asynchronous JavaScript and XML) is the core technology for the front-end to initiate asynchronous requests, and JSON (JavaScript Object Notation) is the common format for data exchange between the front and back ends. This article will use the simplest example to help you understand how Flask interacts with the front end through AJAX and returns JSON data.

1. Basic Concepts: AJAX and JSON

  • AJAX: Also known as Asynchronous JavaScript and XML, it allows the browser to exchange data with the back-end without refreshing the entire page. In simple terms, after clicking a button, the page quietly “background” fetches data and updates partial content.
  • JSON: A lightweight data exchange format, similar to Python dictionaries. It has a simple structure and is easy to parse, making it the “common language” for data transfer between the front and back ends.

2. Core Process of Flask and Front-End Interaction

  1. Front-end Initiates a Request: Send a request to the back-end (e.g., to fetch data or submit a form) via AJAX (e.g., using JavaScript’s fetch or XMLHttpRequest).
  2. Back-end Processes the Request: Flask receives the request and executes business logic (e.g., querying a database, processing data).
  3. Back-end Returns a Response: The back-end returns the result to the front end in JSON format.
  4. Front-end Renders Data: The front end parses the JSON data and updates the page content (e.g., displaying data, updating lists).

3. Practical Example: Front-End Button Triggers AJAX Request, Back-End Returns JSON

We will implement a complete process of “click a button, the back-end returns JSON data, and the front end displays the result” through a simple example.

Step 1: Create a Flask Application

First, install Flask (if not installed):

pip install flask

Then write the Flask code (save as app.py):

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

# Front-end page route (for displaying buttons and result area)
@app.route('/')
def index():
    return render_template('index.html')  # Render the front-end page

# Back-end API route (handles AJAX requests and returns JSON)
@app.route('/api/get_data', methods=['GET'])
def get_data():
    # Simulate business logic: return a JSON data (can be replaced with database queries, etc.)
    data = {
        "status": "success",
        "message": "Hello from Flask!",
        "data": [1, 2, 3, 4, 5]  # Example data list
    }
    return jsonify(data)  # Flask automatically converts the dictionary to JSON format for return

if __name__ == '__main__':
    app.run(debug=True)  # Start the development server

Step 2: Write the Front-End Page (HTML + JavaScript)

Create a templates folder in the root directory of the Flask project and create index.html in it:

<!DOCTYPE html>
<html>
<head>
    <title>Flask AJAX Example</title>
</head>
<body>
    <h1>Flask and Front-End Interaction Example</h1>
    <button onclick="fetchData()">Click to Get Data</button>
    <div id="result"></div>  <!-- Displays the result returned by the back-end -->

    <script>
        // Define the function to fetch data
        async function fetchData() {
            try {
                // 1. Initiate an AJAX request (using the fetch API)
                const response = await fetch('/api/get_data');  // Call the back-end API
                const data = await response.json();  // Parse the JSON data returned by the back-end

                // 2. Process the data and update the page
                const resultDiv = document.getElementById('result');
                resultDiv.innerHTML = `
                    <p>Status: ${data.status}</p>
                    <p>Message: ${data.message}</p>
                    <p>Data List: ${data.data.join(', ')}</p>
                `;
            } catch (error) {
                // Handle request failure
                document.getElementById('result').innerHTML = "Request failed, please try again!";
                console.error("Error:", error);
            }
        }
    </script>
</body>
</html>

Step 3: Run and Test

  1. Ensure the project structure is as follows:
   your_project/
   ├── app.py
   └── templates/
       └── index.html
  1. Run app.py:
   python app.py
  1. Open a browser and visit http://localhost:5000, then click the “Click to Get Data” button to see the JSON data returned by the back-end displayed on the page.

4. Key Knowledge Point Analysis

  1. How the Back-End Returns JSON:
    Flask provides the jsonify function. Just pass a Python dictionary/list, and it will automatically return a JSON-formatted response. If you directly return a dictionary, Flask will handle it automatically, but it is recommended to use jsonify explicitly.

  2. How the Front-End Initiates an AJAX Request:
    The example uses the fetch API (natively supported by modern browsers), which is asynchronous. The async/await syntax simplifies the code. response.json() automatically parses the JSON data and returns a Promise object.

  3. Request Methods and Data Transfer:
    - The example uses a GET request (default). If parameters need to be passed, add them after the URL with ?key=value, or configure method='POST' in fetch and add a body parameter.
    - If the front end needs to pass complex data (e.g., form data), convert the data to a JSON string, and the back end can obtain it via request.get_json():

     @app.route('/api/submit', methods=['POST'])
     def submit_data():
         data = request.get_json()  # Get the JSON data sent by the front end via POST
         return jsonify({"received": data})

5. Summary

Through AJAX and JSON, Flask can easily implement front-end and back-end data interaction. The core steps are: Front-end initiates an asynchronous request → Back-end processes and returns JSON → Front-end parses and renders the data. This pattern is the foundation for building dynamic web applications and can be extended to scenarios such as form submission, database interaction, and real-time data updates.

Extended Exercise: Try modifying the example to implement the front end inputting data (e.g., a name), and the back end returns a personalized response like “Hello, [Name]!”.

(End of the article)

Xiaoye