首页 > 解决方案 > 将 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)

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

标签: javascriptpythonhtmlvariables

解决方案


这是一个使用瓶子框架的例子。要运行它,请使用 安装瓶子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>

推荐阅读