简体   繁体   English

如何读取JSON文件并传输到Z9784E91C7B26579789ZAF组织的HTML中的Javascript?

[英]How to read JSON file and transmit to Javascript in HTML organized by Flask?

I am trying to visualize a bunch of data in JSON format by p5js with a server organized by Flask.我正在尝试通过 p5js 使用由 Flask 组织的服务器以 JSON 格式可视化一堆数据。

Suppose I have a JSON File data.json假设我有一个 JSON 文件data.json

[{"a":"1"},{"b":"2"},{"c","3"}]

And my Python code is:而我的 Python 代码是:

from flask import *

app = Flask(__name__)

def index():
    data_list = json.load(open('data.json'))
    data_json = json.dumps(data_list)
    return render_template("index.html", data_json=data_json)

if __name__ == '__main__':
    app.run(port=7775)

So far I figured out how to send my JSON file to HTML, but how to read the JSON file in HTML through p5js?到目前为止,我想出了如何将我的 JSON 文件发送到 HTML,但是如何读取 JSON 文件到 Z4C4ZDBAD5FCAjsED0381A3F 中的 JSON 文件? Here is my HTML code:这是我的 HTML 代码:

<!DOCTYPE html>
<html>

<head>
    <script src="js/p5.js"></script>
    <script src="sketch.js"></script>
</head>

<body>
    Hello
</body>
</html>

At first, actually, it looks that, in Flask, HTML can't read p5.js and sketch.js correctly.起初,实际上,在 Flask 中,HTML 似乎无法正确读取p5.jssketch.js The error code is Failed to load resource: the server responded with a status of 404 (NOT FOUND)错误代码是Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Second, I can open the JSON file in HTML by {{data_json}} , but how can I transmit to sketch.js so it can be used for visualization?其次,我可以通过{{data_json}}打开 HTML 中的 JSON 文件,但是如何传输到sketch.js以便它可以用于可视化?

What should I do to fix it?我应该怎么做才能修复它? Really appreciate your help!非常感谢您的帮助!

Ideally, your JavaScript would make their own HTTP requests for the data via the Fetch API.理想情况下,您的 JavaScript 将通过获取 API 对数据发出自己的 HTTP 请求。 This allows you to cache the HTML, while keeping that data separate.这允许您缓存 HTML,同时保持数据分离。

In some cases though, it does make sense to build the data directly into the HTML.但在某些情况下,将数据直接构建到 HTML 中确实有意义。 For these times, you can use a script tag and serialize the data as JSON again, inside that script tag.对于这些时候,您可以使用脚本标签并在该脚本标签内再次将数据序列化为 JSON。

So, in your template:因此,在您的模板中:

<script>
  const data = /* your code to serialize and output data here */;
</script>

This sets up the global variable data , which is accessible from your other scripts.这将设置全局变量data ,您可以从其他脚本访问该变量。 Using JSON serialization ensures your data is compatible with JavaScript, without having to worry about any additional escaping.使用 JSON 序列化可确保您的数据与 JavaScript 兼容,而无需担心任何额外的 escaping。 That is, data serialized as JSON can be interpreted by the JavaScript engine, and data will not leak out as arbitrary script.即序列化为JSON的数据可以被JavaScript引擎解释,数据不会作为任意脚本泄露出去。

It's not easy passing python template data to javascript directly so what most people do to achieve the implementation of the functionality of retrieving data is by assigning it to a given html element and querying the element using javascript. It's not easy passing python template data to javascript directly so what most people do to achieve the implementation of the functionality of retrieving data is by assigning it to a given html element and querying the element using javascript.

You can checkout this answer A similar question answered你可以签出这个答案 回答了一个类似的问题

Actually, you don't need any python or libraries.实际上,您不需要任何 python 或库。 You can use this function:您可以使用这个 function:


function readTextFile(file){
    let rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    let txt = '';
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                txt = allText;
            }
        }
    }
  
    rawFile.send(null);
  return txt;
}

and get the content of a file.并获取文件的内容。 use JSON.parse() to turn it into an object:使用JSON.parse()将其变成 object:

let variable = JSON.parse(readTextFile('info.json'))
document.getElementById('hi').innerHTML = variable;

html: <p id='hi'></p> html: <p id='hi'></p>

your html should have the object displayed.您的 html 应该显示 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM