简体   繁体   English

jQuery.getJSON 未与 flask 应用程序一起运行

[英]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.我有一个 flask 应用程序,我正在尝试将一些 json 发送到浏览器并呈现它。 But the line with $.getJSON() is not running.但是$.getJSON()行没有运行。 The jist of which is below:其中的要点如下:

app.py应用程序.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

<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应用程序.js

console.log("before")

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

console.log('after')

Console OUTPUT控制台 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?我在这里不明白什么,为什么getJSON()没有触发?

You are using您正在使用

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

You need to return ONLY data when you call the .getJSON function.当您调用.getJSON function 时,您只需要返回数据。 simple简单的

return data

should work.应该管用。 Because getJSON doesn't allow POST request you'll have to add one more route因为 getJSON 不允许 POST 请求,所以您必须再添加一条路线

@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("/getjson", function(data){
    console.log("during")
    console.log(JSON.stringify(data));
});

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

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