如何使用Apache实现HTML与Python之间的双向数据传输
实现前后端数据传输的修改方案
1. 修改前端HTML代码
你需要在原有代码基础上增加结果展示容器,并用Fetch API替换原有alert逻辑,向Python后端发送请求并接收返回值:
<form id="form" onsubmit="return false;"> <input type="text" id="userInput" value="" placeholder="Enter your move" maxlength="4" /> <input type="submit" onclick="othername();" /> </form> <!-- 新增结果展示容器 --> <div id="resultContainer" style="margin-top: 10px;"></div> <script> function othername() { var move = document.getElementById("userInput").value; // 向Python CGI接口发送POST请求 fetch('/cgi-bin/你的Python文件名.py', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, // 传递用户输入参数 body: 'move=' + encodeURIComponent(move) }) .then(response => response.text()) .then(result => { // 将Python返回的结果展示到页面上 document.getElementById('resultContainer').innerText = '处理结果:' + result; }) .catch(error => console.error('请求出错:', error)); } </script>
注意:请把fetch路径里的
你的Python文件名.py替换成你实际存的Python文件名,比如你把Python文件命名为game.py就写/cgi-bin/game.py。
2. 修改Python CGI代码
你需要导入Python自带的cgi模块来接收前端传递的参数,修改后代码如下:
#!C:\Users\ceqcx\AppData\Local\Programs\Python\Python38\python.exe import cgi # 接收前端传递的表单参数 form = cgi.FieldStorage() # 获取用户输入的move值,没有收到的话就返回默认提示 user_input = form.getvalue('move', '未收到有效输入') # 这里可以插入你自己的游戏逻辑处理代码,比如你原来的游戏处理函数 processed_output = f"收到你的输入:{user_input},游戏逻辑处理完成" # 输出响应头(注意修正了你原来多写的斜杠) print("Content-Type: text/html\n\n") # 输出处理结果,返回给前端 print(processed_output)
3. 运行前检查项
- 确保你的Python文件放在Apache配置的CGI目录下,默认是Apache根目录下的
cgi-bin文件夹 - 确认Apache配置文件httpd.conf中以下配置已开启:
LoadModule cgi_module modules/mod_cgi.so前没有注释符号#- 配置块
<Directory "你的Apache路径/cgi-bin">下有Options +ExecCGI配置 - 新增配置
AddHandler cgi-script .py,让Apache识别Python文件为CGI脚本
- 测试时HTML页面必须通过
http://localhost/xxx.html访问,不要直接双击打开本地HTML文件,否则会触发跨域限制
内容的提问来源于stack exchange,提问作者zdczvbzzbd
相关产品推荐
相关产品推荐

