javascript - jQuery .getJSON 没有与烧瓶应用程序一起运行
问题描述
我有一个烧瓶应用程序,我试图将一些 json 发送到浏览器并呈现它。但是该行$.getJSON()
没有运行。其中的要点如下:
应用程序.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)
索引.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>
应用程序.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
应该管用。因为 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
并将您的getJSON
请求更改为
$.getJSON("/getjson", function(data){
console.log("during")
console.log(JSON.stringify(data));
});
推荐阅读
- android - 如果 json 包含空字符串,则 FCM 推送通知不会到达
- vue.js - Vue.js 一些错误/警告很难调试
- java - 如何在 GET 请求中传递邮递员列表并进入 GetMapping
- python - python中的日期比较
- google-apps-script - 使用脚本在电子邮件中嵌入谷歌表单,就像谷歌在使用选项在电子邮件中包含表单时所做的那样
- typo3 - Typo3 如何获得一个
- 围绕着一个错字链接列表
- angularjs - 在进度条的开始和停止时大声朗读(md-progress-linear)
- svg - 使用过滤器向 svg 多边形添加边框
- java - Spring @Transaction(readOnly = true) 传播到线程
- winapi - Windows 上用户的 GetTempPath