当单击按钮时,我想将数据从 javascript 传递到名为 test.py 的 python 脚本。
该网页包含以下脚本:
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("/cgi-bin/test.py",
{ name: "Zara" };
});
});
});
</script>
<button type="submit">Run</button>
这是在网页的同一服务器上运行的 test.py:
#!/usr/python
print('Content-Type: text/html; charset=utf-8\n')
import sys
file = open('/var/www/cgi-bin/temp.txt','w')
file.write(sys.argv[1])
file.close()
我预计 temp.txt 包含名称 Zara。但 temp.txt 是空的。
所以我的问题是:
python 脚本如何从 javascript 获取参数名称? 我可以使用 sys.argv 还是需要另一个 python 库?
最佳答案
JavaScript 发送常规 HTTP Post 请求,Python 脚本可以将其解析为 regular CGI script :
#!/usr/python
import cgi
print('Content-Type: text/html; charset=utf-8\n')
form = cgi.FieldStorage()
if 'name' in form:
with open('/var/www/cgi-bin/temp.txt','w') as file:
file.write(form['name'])
关于javascript - 如何读取从 javascript post 调用的 python 脚本中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315867/