简体   繁体   中英

Sending JSON data from Flask to Front-end

Is there anybody here with experience in Flask? I am working on my uni project currently, "COVID-19 tracker". At the moment I am trying to send data from Flask to JS and populate a table with that data. But all I get is no results. Please help me. I have to refresh and delete cache, but it does no changes at all.

Flask code:

from flask import Flask, render_template
import requests

app = Flask(__name__)

@app.route('/')
def index():
    world_data_latest = get_world_data()
    return render_template('index.html', world_data_latest = world_data_latest)


def get_world_data():
    url = "https://covid-193.p.rapidapi.com/statistics"

headers = {
    'x-rapidapi-host': "covid-193.p.rapidapi.com",
    'x-rapidapi-key': "51896eb81amsh2a57d7238e4a57ep137532jsn106ff7f478ab"
    }

response = requests.request("GET", url, headers=headers)
return response.json()

if __name__ == "__main__":
    app.run(debug=True)

JavaScript code:

data = JSON.parse('{{ world_data_latest | safe}}')

var table = document.getElementById('world_table');
a = 0
data.forEach(function(object) {
   var tr = document.createElement('tr');
    tr.innerHTML = '<td>' + 0 + '</td>' +
        '<td>' + object.response.country + '</td>' +
        '<td>' + object.response.cases.new + '</td>' +
        '<td>' +  object.response.cases.active + '</td>' +
        '<td>' +  object.response.cases.recovered + '</td>'
        '<td>' +  object.response.cases.recovered + '</td>'
        '<td>' +  object.response.cases.deaths.total + '</td>'
        '<td>' +  object.response.cases.total + '</td>';
   table.appendChild(tr);
});

HTML:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>COVID-19 tracker application</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" src="{{ url_for('static', filename='css/style.css') }}" type="text/css">
    <script rel="stylesheet" src="{{ url_for('static', filename='js/script.js') }}"></script>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light fixed-top navbar-custom">
        <span class="mb-0 h2">COVID-19 tracker</span>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div class="navbar-nav ml-auto">
            <a class="nav-item nav-link active" href="#world">World</span> <span class="sr-only">(current)</span></a>
            <a class="nav-item nav-link" href="#uk">United Kingdom</a>
            <a class="nav-item nav-link" href="#scotland">Scotland</a>
          </div>
        </div>
      </nav>
      <div class="world">
          <div class="table" id="world_table">
            <table class="world_table" id="world_table">
                <thead>
                  <tr>
                    <th scope="col">#</th>
                    <th scope="col">Country</th>
                    <th scope="col">New</th>
                    <th scope="col">Active</th>
                    <th scope="col">Recovered</th>
                    <th scope="col">Deaths</th>
                    <th scope="col">Total</th>
                  </tr>
                </thead>
              </table>
          </div>

      </div>
    </body>
 </html>

I assume that you wish to return a JSON string while making an API request to Flask and use that in the JavaScript side.

You could add an additional app route like the following from which you receive the data in the python side.

@app.route('/testing')
def testing():
    return '{"batman": 1}'

Assuming that you wish to show the text in the HTML side in a div element as shown below.

<div id="receivedData"></div>

You can use the following JavaScript snippet to send a request to the API point we created earlier and display the returned text in the aforementioned HTML element.

const url = window.location.href + 'testing';

fetch(url).then(res => res.json()).then(data => {
   // Printing that data to a div in HTML
   document.getElementById('fullscreen').innerText = data;
})

I hope this will enable you to move forward with your project.

Regards, Zenin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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