簡體   English   中英

jQuery.getJSON 未與 flask 應用程序一起運行

[英]jQuery .getJSON not running with flask app

我有一個 flask 應用程序,我正在嘗試將一些 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')

控制台 OUTPUT

before
after

即使我的數據以某種方式搞砸了,我也希望至少能看到

before
during
after

我在這里不明白什么,為什么getJSON()沒有觸發?

您正在使用

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

當您調用.getJSON function 時,您只需要返回數據。 簡單的

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));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM