javascript - 如何读取从 javascript post 调用的 python 脚本中的数据

标签 javascript jquery python

当单击按钮时,我想将数据从 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/

相关文章:

javascript - Stripe.js - 收集收件人信息

python - Cython hello world 示例在 Windows 上不起作用

尽管安装了 PIP,Python Pillow(或 PIL)仍无法正常工作

javascript - 我的应用程序如何知道 Android 设备是否收到了新消息

javascript - Google DoubleClick for Publishers 失败得太悄无声息

javascript - UI 聊天应用程序中的可点击链接

jquery - jQuery问题分配变量

javascript - 如何使用某个父元素

python - 我的 python 角色一次只移动 1 个像素

javascript - 根据值带填充数组