简体   繁体   中英

jQuery .getJSON not running with flask app

I have a flask application that I am trying to send some json to the browser and render it. But the line with $.getJSON() is not running. The jist of which is below:

app.py

from flask import Flask, render_template


app = Flask(__name__)

@app.route('/')
def index_html():

    data = {"this":"is", "just":"a test"}

    return render_template('index.html', data=data)


if __name__ == '__main__':

    app.run(debug=True)

index.html

<html>
<head>
    <script src="{{url_for('static', filename='jquery-3.5.1.min.js')}}"></script>
    <script src="{{url_for('static', filename='leaflet/leaflet.js')}}"></script>
    <link rel="stylesheet" href="{{url_for('static', filename='leaflet/leaflet.css')}}">
    <link rel="stylesheet" href="{{url_for('static', filename='app.css')}}">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

</head>
<body>
    <h1>My test that doesn't work</h1>
    <div id="llmap"></div>

    <script src="{{url_for('static', filename='app.js')}}"></script>
</body>

app.js

console.log("before")

$.getJSON("/", function(data){
    console.log("during")
    console.log(JSON.stringify(data));
});

console.log('after')

Console OUTPUT

before
after

Even if my data were somehow messed up, i'd expect at least to see

before
during
after

What am I not understanding here, why isn't getJSON() firing?

You are using

return render_template('index.html', data=data)

You need to return ONLY data when you call the .getJSON function. simple

return data

should work. Because getJSON doesn't allow POST request you'll have to add one more route

@app.route('/')
def index_html():
   return render_template('index.html')
@app.route("/getjson")
def json():
   data = {"this":"is", "just":"a test"}
   return data

and change your getJSON request to

$.getJSON("/getjson", function(data){
    console.log("during")
    console.log(JSON.stringify(data));
});

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