mardi 27 décembre 2022

Using info from backend in JS

I'm wondering about getting variables from the Express backend into the JS part of a website. I find myself doing the following a lot:

  • Pass some variable I want to use into res.render
  • Put the variable into the HTML as an invisible element with the template engine, ex. in EJS something like <span id="username" style="display: none;"><%= user.username %></span>
  • Get the variable out in the JS with JQuery, ex: const username = $("#username").text();

But I am wondering if there is a better way...I mean you can't just put anything into the HTML, and I'd prefer to put less just in case...

For example I was making a study course and I wanted to make one call to the DB to get lesson content. But I don't want to put all the lesson content on the page in a hidden element, and I don't want to query the DB for every question. And I don't want to reload the page for every question either, so I'd like to use JS to change the questions...is there some design pattern or common solution for this situation?

Aucun commentaire:

Enregistrer un commentaire