簡體   English   中英

使用外部js文件從flask獲取json

[英]Get json from flask using an external js file

我有一個 flask 服務器吐出 json 數據從 pandas Z6A8064B5CDF4794555570055 轉換而來

[{'name': 'FBtr0075557',
  'score': '164.00'},
 {'name': 'FBtr0075557',
  'score': '162.00'}]

我用來將 dataframe 轉換為 json 的 python 代碼是:

result = df.to_json(orient="records")
parsed = json.loads(result)
return render_template('mirtar.html', targets=json.dumps(parsed))

當我使用內部 javascript 時,數據被解析沒有任何錯誤:

 <script type="text/javascript"> const targets = {{ targets|tojson }}; const entries = JSON.parse(targets); console.log(entries); </script>

但是,當我嘗試使用外部 JS 腳本執行相同操作時,出現錯誤

Uncaught SyntaxError: Unexpected token { in JSON at position

據我了解,這條線

const targets = {{ targets|tojson }};
在外部 javascript 中的行為與內部不同,並且該行的第一個“{”被視為錯誤。 我確信這是一個非常基本的問題,並且必須有一種我肯定錯過的簡單方法。

Jinja syntax is only parsed in flask html templates, not externally loaded JS assets: because it's the python app doing the parsing, and in a deployed environment you'd typically serve static assets with a webserver like nginx.

對此進行排序的最快方法可能是使用此方法,您可以在 HTML 元素中使用數據屬性。 這很感謝您將數據作為參數傳遞給模板render_template ,因此數據在頁面加載存在於模板中。

在您的情況下,這可能看起來像

<!-- a hidden tag -->
<input type='hidden' id='targetid' data-thetargets='{{ targets|tojson }}' />

然后在你的 javascript 中加載它:

var targets = JSON.parse(document.getElementById("targetid").dataset.thetargets);

暫無
暫無

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

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