首页 > 解决方案 > 有没有办法将 python 代码放入 javascript onclick 函数中?

问题描述

我正在尝试将一些 python 代码放入一个 javascript 函数中,以便我可以在单击按钮时调用它。我只是想知道是否有标签或某种内置方式可以在 javascript 函数中对 python 进行编码?我知道我可以通过要求函数打开文件或类似的东西来做到这一点,但是如果有一种方法可以将整个解决方案包含在一个文件中,那就太好了。

这是我试图放入函数的代码:

user_input = input("input text here: ")
cipher_key = int(input("input cipher key here: "))
for x in user_input:
    if x == " ":
        print(x)
    else:
        ord_num = ord(x)
        alf_num = ord_num - 97 + cipher_key
        en_num = alf_num % 26 + 97
        print(chr(en_num))

标签: javascriptpythonhtml

解决方案


这取决于您的环境;如果您正在编写节点 js 程序,您可以按照此处的说明进行操作如何从 Node.js 中执行外部程序?. 如果您正在编写客户端代码(用于 Web 浏览器),则不能 .

编辑

您的代码相对简单,因此您可以将函数转换为 js。假设您正在编写 Nodejs 代码:

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("input text here: ", function(user_input) {
    rl.question("input cipher key here: ", function(cipher_key) {
        rl.close();
        cipher_key = parseInt(cipher_key)
        for (let i = 0; i < user_input.length(); i++) {
            const x = user_input[i];
            if (x === " ")
                process.stdout.write(x)
            else {
                const ord_num = x.charCodeAt(0)
                const alf_num = ord_num - 97 + cipher_key
                const en_num = alf_num % 26 + 97
                process.stdout.write(String.fromCharCode(en_num))

            }
        }
    });
});

推荐阅读