Использовать jsonify
метод.Это позволит вернуть list
из view
.Документация для jsonify .
Ниже приведен пример загрузки данных в шаблон с использованием Javascript.
Структура папки:
├── app.py
├── static
│ └── demo.js
└── templates
└── simple.html
app.py
:
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route("/get_data", methods=['GET'])
def get_data():
data = ["Captain America", "Hulk", "Thor", "Wolverine"]
return jsonify(data)
@app.route("/")
def index():
return render_template("simple.html")
app.run(debug=True)
simple.html
:
<html>
<head>
<title>Marvel Characters</title>
</head>
<body>
<h3>List of Marvel Characters loaded from JS</h3>
<div id="result"></div>
<script src="{{ url_for('static', filename='demo.js') }}"></script>
</body>
</html>
demo.js
:
window.addEventListener("load", function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var result = document.getElementById("result");
for(var i=0;i<data.length; i++){
result.innerHTML += data[i]+"<br>";
}
}
};
xhttp.open("GET", "/get_data", true);
xhttp.send();
});
Выход:
![output of data loading from JS](https://i.stack.imgur.com/HzOQI.png)