Answer the question
In order to leave comments, you need to log in
How to pass a variable from Flask to JavaScript?
Good afternoon.
I have a class:
class Test(db.Model):
__tablename__ = 'test'
__table_args__ = {'schema': 'test_temp'}
a = db.Column(db.String, primary_key=True)
b = db.Column(db.Integer, nullable=False)
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return '[\'a\': \'{}\', \'b\': {}]'.format(self.a, self.b)
def as_dict(self):
return {'a': self.a, 'b': self.b}
@example.route('/report_example', methods=['GET'])
def example():
result = Test.query.all()
result_dict = [r.as_dict() for r in result]
return render_template("static/example.html", result_dict=json.dumps(result_dict))
Answer the question
In order to leave comments, you need to log in
Like this in
html:
<div>
<button id="jsfetch">fetch json</button>
</div>
document.querySelector("#jsfetch").addEventListener("click", Handler);
function Handler(event) {
fetch('/api')
.then((response) => {
return response.json();
})
.then((myjson) => {
console.log(myjson);
});
}
from flask import jsonify
data = {
"id": 123,
"name": "Вася",
"surname": "Пупкин"
}
@app.route('/api')
def api():
return jsonify(data)
Object { id: 123, name: "Вася", surname: "Пупкин" }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question