我有一个flask应用程序,我试图将一些json发送到浏览器并进行渲染。但是带有$.getJSON()
的行未运行。其基本原理如下:
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')
控制台输出
before
after
即使我的数据被弄乱了,我也希望至少能看到
before
during
after
我在这里不明白什么,getJSON()
为什么不触发?
您正在使用
return render_template('index.html', data=data)
调用.getJSON
函数时,仅需要返回数据。简单
return data
应该工作。也许您想在发布请求中返回数据并在get请求中加载页面。所以你应该做
@app.route('/', methods=["POST","GET"])
def index_html():
if request.method== "GET":
return render_template('index.html', data=data)
elif request.method == "POST":
data = {"this":"is", "just":"a test"}
return data