how do i pass a javascript file name to a button click function?

Well you can change the script import like that

  <script type="text/javascript" src="first.json">
    fetch('/first.json')
   .then(response => response.json())
   .then( json => {
      window.products = (window.products || []);
      json.forEach( p => window.products.push(p) );
   });
  </script>

But files must be pure JSON

[
    {
        "name": "Hoodies",
        "description": "This are some hoodies.",
        "price": "90"
    }
]

Rewrite them programmaticaly.

You could also rewrite then like below but it will change all the solution.

{
        "name": "Hoodies",
        "description": "This are some hoodies.",
        "price": "90"
}

And so on… so everything will be available in window.products.

As it can be long to rewrite, you can do it for every file with something like

  <script type="text/javascript" src="first.json">
    Promise.all([ '/first.json', '/second.json']
       .map( file => fetch(file).then( r => r.json() ) )
    )
   .then( allProducts => allProducts.flat() )
   .then( allProducts => window.products = allProducts)
    ;
   });
  </script>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top