您可以从 Flask 路由提供 JSON 文件,并在模板中使用 AJAX 操作路由。
在这里,我使用相同的目录结构重新创建了您的场景,并使用上述方法获得了积极的结果。
server.py:
from flask import Flask, render_template, request, url_for
import os, json
app = Flask(__name__)
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
json_url = os.path.join(SITE_ROOT, "data", "data.json")
data = json.load(open(json_url))
@app.route('/')
def show_index():
return render_template("form.html")
@app.route('/data')
def get_data():
global data
return json.dumps(data)
if __name__ == '__main__':
app.run(debug=True)
form.html 包含 jQuery CDN 和主 js 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="author" content="Ahmedur Rahman Shovon">
<title>JSON Example</title>
</head>
<body>
<div id="result"></div>
<!-- jQuery -->
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>
main.js 文件包含:
$(document).ready(function () {
$.getJSON('/data',function(data, status, xhr){
$("#result").html(data["name"]);
})
})
data.json 包含以下虚拟 JSON 数据:
{
"name": "pumpkin pie",
"ingredients": [" large eggs plus 1 yolk", "1 tsp ground cinnamon"],
"methods": {
"1": "Pre-heat the oven to 200C/400F/Gas 6",
"2": "If using a shop bought sweet crust pastry case, use one that is 23cm/9in diameter and 4cm/1.5in deep. If using your own pastry, roll it out and use it to line a 23cm/9in pie plate (not loose bottomed). Bake the pastry case blind for 20 minutes."
}
}
输出: