首页 > 解决方案 > 将变量从 python 文件发送到 javascript,然后发送到单独的 HTML 文件?

问题描述

我正在尝试创建一个 chrome 扩展,主要代码在 python 中,但我很挣扎。我已经成功地将用户从 HTML 端输入的信息发送到 python 脚本,但不是相反。这是我到目前为止所拥有的(或似乎是问题的代码):

Python:

@app.route('/get_data', methods = ['POST'])
def get_data():
    taken = request.get_data()
    taken2 = taken.decode()
    print(taken2)
    strength = int(taken2)   #this works, I use this later in the code
    my_variable = 5                    #just for example 
    return jsonify(my_variable), 200

背景.js (javascript)

function myAction(input) { 
    console.log("input value is : " + input.value);

        newish = input.value

        var xxhttp = new XMLHttpRequest();
        xxhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
        xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
        xxhttp.send(newish);


       //so sending newish here works, this shows up on my python console (strength becomes this)

HTML

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="button.css">
    <script src="background.js" type="text/javascript">


    </script>     

       
  </head>
  <body>
    <h1>A Thing!</h1>

    <div style="padding: 20px 20px 20px 20px;">           
        <h3>Hello,</h3>
        <p>User input please? : </p>         
        <input id="name_textbox" />                   
        <button id="ok_btn" type="button">OK</button>
    </div>   

  </body>


</html> stuff



我的目标是让 my_variable 以某种方式被接受到 javascript 文件中,然后 html 能够访问和显示 my_variable 的内容。我试过环顾四周,但似乎没有地方有我正在寻找的确切东西(将 python 变量发送到单独的 html 文件以进行 chrome 扩展)。我有点茫然,任何帮助将不胜感激,谢谢!

标签: javascriptpythonhtmlgoogle-chrome-extension

解决方案


更好的方法

由于您想通过读取文件将变量从 python 发送到 html,这比在 javascript 中使用 FS 模块更好。

示例 index.html 代码:

<body>
    <h1>Hello, {first_header:}!</h1>
    <p>{p2:}, {p1:}</p>
</body>

以上的python代码:

newFileCode = open("index.html", "r").read().format(first_header='goodbye', 
                                         p1='World', 
                                         p2='Hello')
open("index.html", "w").write(newFileCode)

在 HTML 文件中输出:

<body>
    <h1>Hello, goodbye!</h1>
    <p>Hello, World</p>
</body>

在此处阅读有关 python 中文件处理的更多信息

以前的答案

您可以使用 JSON 解析数据。虽然,您需要一个新的 Node.js 模块 fs https://nodejs.org/api/fs.html。安装该模块后,您必须维护两个 JSON,一个是 JS 变量,另一个是外部 .json 文件。

使用此代码在 javascript 中写入外部 JSON 文件:

fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));

使用此代码在 javascript 中读取外部 JSON 文件:

JSON.parse(fs.readFileSync(name).toString())


要在 python 中从外部 JSON 文件中获取/读取数据,请使用以下代码:

import json
  
# Opening JSON file
f = open('fileName.json',)
  
# returns JSON object as 
# a dictionary
data = json.load(f)
  
# Iterating through the json
# list
for i in data['emp_details']:
    print(i)
  
# Closing file
f.close()

您可以从 javascript 编辑文件,并可以使用 while 循环在 python 中读取它


推荐阅读