首页 > 解决方案 > 在 javascript 中使用 python 输出

问题描述

我们想将一个布尔值从 python 发送到 javascript,以便我们可以在我们的 html 网站中使用它。

我们尝试使用套接字,但这对我们来说太复杂了。我们的下一个想法是使用 api,我们知道如何使用 javascript 从 api 获取信息。我们要做的是将python布尔值发布到api,然后使用javascript从api中获取布尔值。但我们不知道该怎么做。

我们为所有代码使用树莓派,并在按下时在 python 中返回 true 的硬件按钮。

我们目前正在测试从https://healeycodes.com/javascript/python/beginners/webdev/2019/04/11/talking-between-languages.html找到的代码

但是这段代码对我们不起作用。我们也在使用pycharm作为我们的工作空间,这是一个问题吗?

我们当前的javascript代码:

    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }
    };
    request.send();
     setInterval(get("button-status.json", receiveStatus), 3000);
}


function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
// checks every 100ms
get()

我们用于测试的python代码:

import random
import json
import time
button_status = False
path = (r"C:\Users\Sam\Desktop\pythonProject\pythonflask\emplates")  # replace with your actual path

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)



while True :
    value = random.randrange(1, 10)
    if ( value <= 5) :
        button_status = True
        save_button_status()
        time.sleep(3)
    else :
        button_status = False
        save_button_status()
        time.sleep(3)

    print(button_status)

标签: javascriptpythonapiraspberry-piapi-design

解决方案


网页中的 Javascript 不能直接在您的计算机上运行 Python 脚本或从本地终端读取信息。您可以做的是让您的 Python 程序将一个小的 json 文件输出到您的 localhost 文件夹,当按下或释放按钮时,该文件夹会被覆盖,如下所示:

import json
button_status = False   # assuming it is initially off
path = "path/to/your/localhost/folder"  # replace with your actual path

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)

# Then call save_button_status() whenever the status changes

然后在您的 javascript 中,设置一个间隔以定期调用一个获取此 json 文件的函数,并根据该值(如果它已更改)执行某些操作:

function get(url, success) {
    //--- Get JSON data at the given URL and call `success` if successful
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }   
    };
    request.send();
}

function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
let interval = setInterval(() => get("button-status.json", receiveStatus), 100); // checks every 100ms

当您的本地服务器更新文件时,可能会有一些延迟。


推荐阅读