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}


And a function that returns JSON:
@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))


How can I pass the result to JavaScript and store it in a variable ?
In HTML it's simple, using "{{result}}", and JavaScript is something not working.
Help, please.
April 4th 20 at 13:07
1 answer
April 4th 20 at 13:09
Solution
That's about

html:
the <div>
 <button id="jsfetch">fetch json</button>
 </div>

js:
document.querySelector("#jsfetch").addEventListener("click", Handler);
function Handler(event) {
fetch('/api')
 .then((response) => {
 return response.json();
})
 .then((myjson) => {
console.log(myjson);
});
}


flask:
from flask import jsonify
data = { 
 "id": 123,
 "name": "Vasya",
 "surname": "DOE"
}

@app.route('/api')
def api():
 return jsonify(data)


Start, press the button and see the browser console:
Object { id: 123, name: "Bob", surname: "DOE" }

Find more questions by tags jQueryFlask