sergio.canzoneri
sergio.canzoneri

Reputation: 1

Loading content dynamically from JSON file to HTML page through JS

I'm trying to create an online bookshop website and, since I don't have to fetch data from a database, I've thought about loading my book-objects from a JSON file. What I should do is: loading the objects from the JSON file and building dynamically the pages (e.g. a page with a list of all the available books, another one with a search bar with filters and so on). I've recently started to study HTML, CSS, JS (and Node.JS), so I'm not really sure about what I can actually do and what I can't. I've read online that I could use JQuery in my HTML file to load the JSON from the URL, but still I was wondering: is there any chance that I can load the JSON content in my JS file (maybe through path and fs as in Node.JS) and use it like dynamic content (e.g. through .innerHTML)?

Upvotes: 0

Views: 4862

Answers (1)

Gulielmus
Gulielmus

Reputation: 91

You don't need server side code for this.

Let's assume you have a JSON file called books.json in the same directory as your javascript file:

{
  "books": [
    {"title": "book1", "author": "author1"},
    {"title": "book2", "author": "author2"}
  ]
}

And a index.html:

<div id="books"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="script.js"></script>

In your script.js, you can load the JSON like this with jQuery:

// global variable
var data;

$.get('books.json', function(d) {
  data = JSON.parse(d);
  // loop through all books
  data.books.forEach(function(b) {
    // now you can put every book in your <div>
    $("#books").append(`<div><h2>${b.title}</h2><p>${b.author}</p></div>`);
  });
});

The search function could go like this:

html:

<input id="input" /><button onclick="search()">search</button>

javascript:

function search() {
  $("#books").html("");
  let search = $("#input").val();
  // filter the data
  let filtered = $(data).filter(function (i,b){return b.title == search || b.author == search});
  filtered.books.forEach(function(b) {
    $("#books").append(`<div><h2>${b.title}</h2><p>${b.author}</p></div>`);
  });
}

Upvotes: 1

Related Questions