gpt4 book ai didi

javascript - 将 HTML/JS 变量传递给 Python

转载 作者:行者123 更新时间:2023-12-03 01:29:54 24 4
gpt4 key购买 nike

我正在创建一个将在嵌入式设备上运行的网站,该设备为用户提供与网站上的多个功能进行交互的界面。 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)

有没有办法在不重新加载网页的情况下发送查询字符串?我不希望每次用户单击按钮时都重新加载页面,因为他们会经常这样做。

最佳答案

这是一个使用 Bottle 框架的示例。要运行此程序,请使用 pip install Bottle 安装 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)

index.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>

关于javascript - 将 HTML/JS 变量传递给 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51351065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com