javascript - 将 HTML/JS 变量传递给 Python
问题描述
我正在创建一个将在嵌入式设备上运行的站点,该设备为用户提供与站点上的多个功能进行交互的界面。HTML 站点上的这些函数将与 Python 脚本交互,该脚本将控制连接到嵌入式设备的外部物理设备。
到目前为止,我有几个如下所示的按钮:
<button class="ui left attached button white" value="Button A - OFF" onClick='buttonTrigger(this.value)'>Button A</button>
buttonTigger.js 方法如下所示:
function buttonTrigger(value) {
document.location = "cgi-bin/command.cgi"
}
command.cgi 如下所示:
#!/bin/bash
echo "Hello World!"
我的最终目标是让 .cgi 脚本将按下的按钮的值传递给 Python 脚本。
这是我的问题:如何从 buttonTrigger.js 调用 command.cgi 并将value
参数从传递buttonTrigger
给方法?我的 Python 脚本将如何访问传递给 .cgi 脚本的变量?或者,我的 Python 脚本如何在没有 .cgi 脚本的情况下直接从 JS 访问变量值?
编辑:所以 Bottle 有能力处理查询字符串:
from bottle import route, request, response, template
@route('/forum')
def display_forum():
forum_id = request.query.id
page = request.query.page or '1'
return template('Forum ID: {{id}} (page {{page}})', id=forum_id, page=page)
有没有办法在不重新加载网页的情况下发送查询字符串?我不希望每次用户单击按钮时都重新加载我的页面,因为他们会经常这样做。
解决方案
这是一个使用瓶子框架的例子。要运行它,请使用 安装瓶子pip install bottle
,然后使用 启动应用程序python app.py
,这将http://localhost:8000/
默认运行应用程序。
应用程序.py
from bottle import request, route, run, static_file
@route('/')
def index():
return static_file('index.html', './')
@route('/command')
def command():
value = request.query.value
return 'Value was set to: ' + value
run(host='0.0.0.0', port=8000, debug=True)
索引.html
<!doctype html>
<html>
<head>
<title>Python Example</title>
<script>
function buttonTrigger(value) {
var output = document.getElementById('output');
output.innerText = 'Button clicked, waiting for response...';
fetch('command?value=' + value)
.then(function(response) {
return response.text();
})
.then(function(text) {
console.log(text);
output.innerText = text;
});
}
</script>
</head>
<body>
<button value="Button A - OFF" onClick='buttonTrigger(this.value)'>Button A</button>
<div id="output"></div>
</body>
</html>
推荐阅读
- twitter-bootstrap - 如何在 Domino 中使用 Bootstrapthemes?
- python - Python——函数的可选参数
- azure - Azure 生命周期管理 - 区域
- httpclient - 无法在 HttpClient 中设置授权标头(.Net core 3.1)
- node.js - 节点 js 中的 pg 7.18.0 不起作用,抛出:不推荐使用隐式禁用证书验证,并将在 pg 8 中删除
- javascript - 如何将多个字符串添加到列表中
财产? - excel - Pandas 扫描目录以修复多个损坏的 excel 文件;将所有或少数固定文件合并到一个数据框中
- java - Firebase 回收站视图中的 Searchview 为空
- iis - IIS 10 中 IIS 高级日志记录功能的替代方案
- javascript - 将两个或多个数据绑定到 VueJs 中的表单输入