从Python(Flask)向JavaScript发送数据可以通过以下几种方式实现:
示例代码:
# Flask路由
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/data', methods=['POST'])
def send_data():
data = request.get_json() # 获取前端发送的数据
# 处理数据...
response = {'message': 'Data received successfully'}
return jsonify(response)
if __name__ == '__main__':
app.run()
// JavaScript代码
var data = { 'name': 'John', 'age': 25 };
$.ajax({
url: '/data',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(response) {
console.log(response.message);
}
});
示例代码:
# Flask-SocketIO示例
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(data):
# 处理数据...
response = {'message': 'Data received successfully'}
emit('response', response)
if __name__ == '__main__':
socketio.run(app)
// index.html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>
<script>
var socket = io();
socket.on('connect', function() {
console.log('Connected');
});
socket.on('response', function(response) {
console.log(response.message);
});
function sendMessage() {
var data = { 'name': 'John', 'age': 25 };
socket.send(data);
}
</script>
</head>
<body>
<button onclick="sendMessage()">Send Message</button>
</body>
</html>
示例代码:
# Flask模板引擎示例
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
data = { 'name': 'John', 'age': 25 }
return render_template('index.html', data=data)
if __name__ == '__main__':
app.run()
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Python to JavaScript Example</title>
<script>
var data = {{ data|tojson }};
console.log(data);
</script>
</head>
<body>
<!-- 页面内容... -->
</body>
</html>
以上是从Python(Flask)向JavaScript发送数据的几种常见方式,具体选择哪种方式取决于你的需求和项目的特点。
领取专属 10元无门槛券
手把手带您无忧上云