XAMPP环境下如何将网页变量传递至Python?能否使用Flask?
嘿,完全没问题!XAMPP环境下绝对可以用Flask来实现HTML页面到Python的变量传递,我给你梳理一套清晰的实操步骤:
1. 先搞定Flask的安装
首先确认你的XAMPP里有没有自带Python——有些版本的XAMPP会集成Python,你可以在XAMPP控制面板的Shell里输入python --version或者python3 --version看看。如果没找到,就自己装个Python,然后在命令行里执行pip install flask(或者pip3)完成安装。
2. 写一个简单的Flask后端接口
创建一个叫app.py的文件,内容大概这样:
from flask import Flask, request, jsonify app = Flask(__name__) # 允许跨域(如果HTML在Apache的80端口,Flask在5000端口的话需要这个) from flask_cors import CORS CORS(app) # 处理GET请求的接口 @app.route('/get-data', methods=['GET']) def get_data(): # 从URL参数里拿变量,比如http://localhost:5000/get-data?username=Antonio&age=25 username = request.args.get('username') age = request.args.get('age') print(f"收到GET请求:username={username}, age={age}") # 可以返回处理后的结果给HTML return jsonify({"status": "success", "message": f"你好,{username}!"}) # 处理POST请求的接口(更适合传递敏感数据或大量数据) @app.route('/post-data', methods=['POST']) def post_data(): # 从表单或JSON里拿变量 username = request.form.get('username') age = request.form.get('age') # 如果是JSON格式的请求,用request.get_json() # data = request.get_json() # username = data.get('username') print(f"收到POST请求:username={username}, age={age}") return jsonify({"status": "success", "data": {"username": username, "age": age}}) if __name__ == '__main__': app.run(debug=True) # debug模式方便开发,上线要关掉
别忘了如果用跨域的话,要装flask-cors:pip install flask-cors
3. 修改你的HTML页面,发送数据到Flask
有两种常见方式:
方式一:用表单提交(同步刷新页面)
<!DOCTYPE html> <html> <body> <form action="http://localhost:5000/post-data" method="POST"> 用户名:<input type="text" name="username"><br> 年龄:<input type="number" name="age"><br> <button type="submit">提交</button> </form> </body> </html>
方式二:用AJAX异步发送(页面不刷新)
<!DOCTYPE html> <html> <body> 用户名:<input type="text" id="username"><br> 年龄:<input type="number" id="age"><br> <button onclick="sendData()">提交</button> <div id="result"></div> <script> function sendData() { const username = document.getElementById('username').value; const age = document.getElementById('age').value; fetch('http://localhost:5000/post-data', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `username=${username}&age=${age}` }) .then(response => response.json()) .then(data => { document.getElementById('result').innerHTML = `提交成功!返回数据:${JSON.stringify(data)}`; }) .catch(error => { console.error('错误:', error); }); } </script> </body> </html>
4. 启动服务测试
- 先打开XAMPP控制面板,启动Apache服务,把你的HTML文件放到XAMPP的
htdocs文件夹里(比如htdocs/test.html)。 - 打开命令行,进入
app.py所在的文件夹,执行python app.py启动Flask服务。 - 在浏览器里访问
http://localhost/test.html,输入数据提交,然后看Flask的终端输出,就能看到变量已经传过来了!
额外小提示
如果不想处理跨域问题,你可以把HTML文件放到Flask项目的templates文件夹里,然后用Flask的render_template来返回页面,这样HTML和Flask就在同一个端口(5000)下,就不会有跨域问题了。比如修改app.py:
from flask import render_template @app.route('/') def index(): return render_template('test.html')
然后把HTML放到templates/test.html,访问http://localhost:5000就能打开页面了。
内容的提问来源于stack exchange,提问作者AntonioMJ
相关产品推荐
相关产品推荐

