html传参到flask
时间: 2024-12-14 22:10:47 浏览: 6
在HTML页面中传递参数到Flask后端,通常有以下几种方法:
1. **GET请求**:通过URL传递参数。
2. **POST请求**:通过表单提交数据。
3. **AJAX请求**:通过JavaScript发送异步请求。
下面是一个简单的示例,展示了如何在HTML页面中使用GET和POST方法将参数传递到Flask后端。
### 使用GET方法
**HTML页面(index.html)**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GET Method Example</title>
</head>
<body>
<form action="/get-data" method="get">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>
```
**Flask应用(app.py)**:
```python
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get-data')
def get_data():
username = request.args.get('username')
return f'Hello, {username}!'
if __name__ == '__main__':
app.run(debug=True)
```
### 使用POST方法
**HTML页面(index.html)**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>POST Method Example</title>
</head>
<body>
<form action="/post-data" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>
```
**Flask应用(app.py)**:
```python
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/post-data', methods=['POST'])
def post_data():
username = request.form['username']
return f'Hello, {username}!'
if __name__ == '__main__':
app.run(debug=True)
```
### 使用AJAX方法
**HTML页面(index.html)**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Method Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="ajax-form">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
<div id="response"></div>
<script>
$(document).ready(function() {
$('#ajax-form').submit(function(event) {
event.preventDefault();
var username = $('#username').val();
$.ajax({
url: '/ajax-data',
type: 'POST',
data: { username: username },
success: function(response) {
$('#response').text(response);
}
});
});
});
</script>
</body>
</html>
```
**Flask应用(app.py)**:
```python
from flask import Flask, request, render_template, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ajax-data', methods=['POST'])
def ajax_data():
username = request.form['username']
return jsonify(f'Hello, {username}!')
if __name__ == '__main__':
app.run(debug=True)
```
阅读全文