L
L
lrv2020-01-21 09:58:11
JavaScript
lrv, 2020-01-21 09:58:11

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 do I pass the result to JavaScript and store it in a variable?
In HTML, everything is simply done, through "{{result}}", and JavaScript does not work.
Help me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iddqda, 2020-01-21
@lrv

Like this in
html:

<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": "Вася",
    "surname": "Пупкин"
}

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

You run it, click on the button and see in the browser console:
Object { id: 123, name: "Вася", surname: "Пупкин" }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question