【Copilotの答えの始め】

 

Flask と Ajax を使ったシンプルな例を示します。まず、Flask アプリケーションを作成し、次に Ajax を使用してデータを送信し、Flask 側で処理する仕組みを紹介します。

1. Flask アプリケーションの設定

まず、Flask アプリケーションを作成します。以下のようなファイル構成になります:

1
2
3
4
project/
├── app.py
├── templates/
│   └── index.html

app.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from flask import Flask, request, jsonify, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process', methods=['POST'])
def process():
    data = request.json
    name = data.get('name')
    response = {'message': f'Hello, {name}!'}
    return jsonify(response)

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

2. HTML と Ajax の設定

次に、Ajax を使用してデータを送信する HTML ファイルを作成します。

templates/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask Ajax Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Flask Ajax Example</h1>
    <form id="myForm">
        <input type="text" id="name" placeholder="Enter your name">
        <button type="submit">Submit</button>
    </form>

    <p id="response"></p>

    <script>
        $(document).ready(function() {
            $('#myForm').on('submit', function(event) {
                event.preventDefault();
                let name = $('#name').val();
                $.ajax({
                    url: '/process',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({name: name}),
                    success: function(response) {
                        $('#response').text(response.message);
                    }
                });
            });
        });
    </script>
</body>
</html>

これで、ブラウザ上でフォームに名前を入力し、送信ボタンをクリックすると、Ajax によってデータが Flask アプリケーションに送信され、返されたメッセージが画面に表示されます。

 

【Copilotの答えの始め】

 

 

 

 

死ぬ夢を見て母の腕新豆腐