简体   繁体   中英

Getting data from python flask to html through Javascript

I am learning data science but I am still new to flask, html and Js. I have developed a ML model for home price prediction and would love to deploy it to Heroku.

The problem is the drop down menu in my frontend is not updated by the locations I have passed in my python flask backend.

here are the important parts of my code.

server.py:

from flask import Flask, request, jsonify, render_template
app = Flask(__name__)

@app.route('/locations')
def locations():
    response = jsonify({
        'locations': get_location_names()
    })
    response.headers.add('Access-Control-Allow-Origin', '*')

    return response

app.js

function onPageLoad() {
  console.log( "document loaded" );
  $.get("{{ url_for('locations') }}",
  function(data, status) {
  console.log("got response for locations request");
  if(data) {
      var locations = data.locations;
      var uiLocations = document.getElementById("uiLocations");
      $('#uiLocations').empty();
      for(var i in locations) {
          var opt = new Option(locations[i]);
          $('#uiLocations').append(opt);
      }
  }
  });

index.html:

<!DOCTYPE html>
<html>
<head>
<title>Banglore Home Price Prediction</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" 
       type="text/javascript"></script>
<link rel="stylesheet" type= "text/css" href="{{url_for('static', filename = 'app.css')}}">
<script type="text/javascript" src ="{{url_for('static', filename = 'app.js')}}"></script>
</head>

the browser consoles prints "document loaded" which I placed in app.js but doesn't get the data from server.py. I believe the issue is with the url_for statement but don't know how to go about it.

You can't use jinja2 expressions in a js file which is loaded as a static asset. - v25

You can add your Javascript in a <script> tag in the index.html file. Or you can hard code it.

I usually do not use either approachs. Instead, I render all the files with a custom python script before running the main app. I use a.bat file and type all the commands needed. You sometimes use Sass or any other thing that requires rendering... So it's helpful to be organized and write such a script. Use this approach if your JavaScript data doesn't change dynamically.

But if your script is dynamic, you can add a route that renders your file every time it is requested.

@app.route('/my_script.js')
def script():
    return render_template('my_script.js', name='mark')

And in your /locations route:

<script src="{{url_for('script')}}"></script>

Jinja2 can parse any file regardless of it's type.

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