简体   繁体   中英

how to access the data sent from server(using flask), in javascript code?

from my server I sent a data like this to my front end,

return render_template("home.html", username=username)

I can access this data in the HTML using {{ username }}

But if I want to use this in javascript code(in script tags) how would I do that?

In order to use the data fetched from a Flask server in script tags, you have to convert the object into JSON representation which you can easily do by using Flask's tojson() template filter. For more info about tojson() visit this link .

Solution to your problem -

<script>
    var username = JSON.parse('{{ username | tojson | safe}}');
    //you can now use it in whichever way you want to
</script>

Hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM