简体   繁体   English

返回 Json object 到 HTML

[英]Return Json object to HTML

I'm developing a web app where I need to update the configuration of a certain type of graph.我正在开发一个 web 应用程序,我需要在其中更新某种类型图形的配置。 To do so, I'm using Python3 with flask and html.为此,我将 Python3 与 flask 和 html 一起使用。

I want to update the configuration dynamically, which means that I don't want to use the function render_template and instead, I want to use return jsonify(message) .我想动态更新配置,这意味着我不想使用 function render_template而是想使用return jsonify(message)

Below I included the function that I want to use to update the data.下面我包含了我想用来更新数据的 function。 This function is used as a callback on the rest of my system and those prints are being executed well, which means that on the flask side, everything seems to be okay.这个 function 用作我系统的 rest 的回调,并且这些打印正在执行良好,这意味着在 flask 方面,一切似乎都很好。 However, I don't know what I should put on the html side to receive this data.但是,我不知道应该在 html 端放什么来接收这些数据。 Here is the code that I'm using in flask to send the data :这是我在 flask 中用于发送数据的代码:

@app.route('/online_visualization_update')
def online_visualization_update(msg):
    print("I should change the network.")
    print("The message was ", msg)
    with app.app_context():
        return jsonify(msg.transition, msg.marking)

This is the code I tried to implement on html to receive the data sent by flask:这是我尝试在 html 上实现以接收flask 发送的数据的代码:

<script type=text/javascript>

fetch('/online_visualization_update')
         .then(response => response.json())
         .then(data => console.log(data))
         .catch((error) => {console.error('Error:', error);
});

</script>

Currently, this is not working because the the fetch is being performed every time I open the webapp.目前,这不起作用,因为每次打开 web 应用程序时都会执行获取。 What am I doing wrong?我究竟做错了什么?

Ideally, I would like to have a function on javascript that is executed only when it receives the data from flask but I don't know whether fetch works like that or not.理想情况下,我想在 javascript 上有一个 function ,它仅在从 flask 接收数据时执行,但我不知道 fetch 是否像那样工作。

Thank you谢谢

For that you need to use Fetch API in javascript like this为此,您需要像这样在 javascript 中使用 Fetch API

  // write function like this
  function callApi(){
    fetch('/online_visualization_update')
     .then(response => response.json())
      .then(data => console.log(data))
    .catch((error) => {
      console.error('Error:', error);
    });
   }

Refer this for more about fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch有关获取的更多信息,请参阅此: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Add this code in your Html page:在您的 Html 页面中添加此代码:

   <Div class="container">
            <button type="button" onclick="callApi()">Call func</button>
            <!--you need to call function like this whenever you need data -->
    </Div>

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

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