Home > Back-end >  Can you store js code on the fly in a variable and have js read it?
Can you store js code on the fly in a variable and have js read it?

Time:08-25

I'm not sure if what I'm trying to do is the correct/valid approach to what I'm trying to accomplish; essentially, I'm retrieving data from a db via an ajax call, I want this data to populate a js library where the layout is something like

data[
 item{
   name: 'name',
   start_date: date,
   end_date: date
 },
item{
   name: 'name',
   start_date: date,
   end_date: date
 },
]

is there any way I can populate the code inside 'data' on the fly? I was thinking with a loop to populate a variable which would hold the data and placing it like so

//this is hard coded, but the idea is that a loop would populate this with the necessary information
let items = "
item{
   name: 'name',
   start_date: date,
   end_date: date
 },
item{
   name: 'name',
   start_date: date,
   end_date: date
 }";

data[
 items 
]

Would this be a valid approach? thanks in advance!

CodePudding user response:

It seems you are asking if you can import data from a database and populate a JSON array in Javascript with it. The answer would be yes. In fact, I do this routinely to create Javascript front ends that can be quickly rendered and only talk to the database when necessary so you're not waiting on it. You can use Jquery ajax calls to retrieve and write data. I like to have local variables with JSON formatted data which I use to run the app. The app can quickly read and write changes to these JSON arrays. Keep in mind if the page is reloaded or fails all the data to that point will be lost and the user will have to start over so you need to store data to the database at strategic intervals. You can also use HTML localStorage to store data in the browser itself. I've found this an efficient way to build single-page Javascript apps without resorting to React or some of the other frameworks. It's not as efficient though, but easier to code and maintain.

CodePudding user response:

The approach I would take is to define a particular DOM element as a parent / container for the DOM elements which will represent each item. Iterate over the items array in your ajax response, and create DOM elements with jquery for each item. Something along the lines of $('<div>${currentItem.name}>/div>').appendTo(containerDiv);

  • Related