0

I need to make HTML fill itself with content from JSON file using Mustache or Handlebars.

I created two simple HTML templates for testing (using Handlebars) and filled them with content from an external JavaScript file. http://codepen.io/MaxVelichkin/pen/qNgxpB

Now I need content to lay initially in a JSON file.

I ran into two problems, but they both lie at the heart of solutions of the same main problem - creating a link between the content in the JSON file and HTML, so I decided to ask them in the same question.

  1. How can I connect JSON and HTML? As far as I know there is a way, using AJAX, and there's a way that uses a server. AJAX is a new language for me, so I would be grateful for an explanation of how can I do it, using local HTTP server, that I created using Node.JS.

  2. What should be the syntax in a JSON file? The script in the JSON file must be the same, as a script in JavaScript file, but then it should be processed with the help of JSON.parse function, is that correct? Or syntax in JSON file should be different?

    For example, if we consider my example (link above), the code for the first template in the JSON file must be the same as in the JavaScript file, but before the last line document.getElementById('quoteData').innerHTML += quoteData;, I have to write the following line var contentJS = JSON.parse(quoteData);, and then change the name of the variable in the last line, so it will be: document.getElementById('quoteData').innerHTML += contentJS;, Is it right?

Community
  • 1
  • 1
Rumata
  • 1,027
  • 3
  • 16
  • 47

2 Answers2

1

Try this:

HTML:

<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
  Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b></span>
</script>

JS:

function sendGet(callback) {
    /* create an AJAX request using XMLHttpRequest*/
    var xhr = new XMLHttpRequest();
    /*reference json url taken from: http://www.jsontest.com/*/

    /* Specify the type of request by using XMLHttpRequest "open", 
       here 'GET'(argument one) refers to request type
       "http://date.jsontest.com/" (argument two) refers to JSON file location*/
    xhr.open('GET', "http://date.jsontest.com/");

    /*Using onload event handler you can check status of your request*/
    xhr.onload = function () {
        if (xhr.status === 200) {
            callback(JSON.parse(xhr.responseText));
        } else {
            alert(xhr.statusText);
        }
    };

    /*Using onerror event handler you can check error state, if your request failed to get the data*/
    xhr.onerror = function () {
        alert("Network Error");
    };

    /*send the request to server*/
    xhr.send();
}

//For template-1
var dateTemplate = document.getElementById("date-template").innerHTML;
var template = Handlebars.compile(dateTemplate);

sendGet(function (response) {
    document.getElementById('testData').innerHTML += template(response);
})

JSON:

JSON data format derives from JavaScript, so its more look like JavaScript objects, Douglas Crockford originally specified the JSON format, check here.

JavaScript Object Notation has set of rules.

  1. Starts with open curly braces ( { ) and ends with enclosing curly braces ( } ) ex: {}

  2. Inside baces you can add 'key' and its 'value' like { "title" : "hello json"} here "title" is key and "hello json" is value of that key.

  3. "key" should be string

  4. "value" can be:
    number
    string
    Boolean
    array
    object

  5. Can not add JavaScript comments inside JSON (like // or /**/)

there are many online JSON validators, you can check whether your JSON is valid or not, check here.


When comes to linking JSON to js file, its more like provide an interface to get JSON data and use it in your JavaScript.

here XMLHttpRequest our interface. we usually call XMLHttpRequest API.

In the given js code, to get JSON from the server using an REST API (http://date.jsontest.com/)

for more information on REST API you can check here

from the url: http://date.jsontest.com/ you can get JSON object like below.

{
   "time": "03:47:36 PM",
   "milliseconds_since_epoch": 1471794456318,
   "date": "08-21-2016"
}
Note: data is dynamic; values change on each request.

So by using external API you can get JSON, to use it in your JavaScript file/ code base you need to convert JSON to JavaScript object,
JSON.parse( /* your JSON object is here */ ) converts JSON to js Object

`var responseObject = JSON.parse(xhr.responseText)`

by using dot(.) or bracket ([]) notation you can access JavaScript Object properties or keys; like below.

console.log(responseObject.time) //"03:47:36 PM"
console.log(responseObject["time"]) //"03:47:36 PM"

console.log(responseObject.milliseconds_since_epoch) //1471794456318
console.log(responseObject["milliseconds_since_epoch"])//1471794456318

console.log(responseObject.date) //"08-21-2016"
console.log(responseObject["date"]) //"08-21-2016"

So to link local JSON file (from your local directory) or an external API in your JavaScript file you can use "XMLHttpRequest".

'sendGet' function updatedin the above js block with comments please check.

In simple way:

  1. create XMLHttpRequest instance
    ex: var xhr = new XMLHttpRequest();
  2. open request type
    ex: xhr.open('GET', "http://date.jsontest.com/");
  3. send "GET" request to server
    ex: xhr.send();
  4. register load event handler to hold JSON object if response has status code 200. ex: xhr.onload = function () {

for more info check here


Know about these:

  • Object literal notation
  • difference between primitive and non-primitive data types

Existing references:

Community
  • 1
  • 1
Naresh S
  • 359
  • 3
  • 6
  • Thank you very much! And what code should be in the json file? And how to link json file and javascript file? I'm new to this approach, could you explain to me step by step, please? – Rumata Aug 21 '16 at 15:32
  • answer edited based on your comment, please check and let me know you need more information. – Naresh S Aug 21 '16 at 18:09
  • Wow, thank you very much for such a detailed answer! I will begin to study it and try implement it. Can I ask you questions if they arise in the process? – Rumata Aug 21 '16 at 23:10
  • Thank you again for your help! I have a small additional question: If I need to take, not all the content from the JSON file, but only one object, how can I do it? I tried to use the code from Your answer, changing the `xhr.onload = function` : – Rumata Sep 04 '16 at 17:42
  • ` var responseObject = JSON.parse(xhr.responseText); console.log(responseObject.header); callback(responseObject.header);` – Rumata Sep 04 '16 at 17:43
  • As the result I see in the console that is exactly the content I need, but it does not appear on the page, apparently I made a mistake? – Rumata Sep 04 '16 at 17:43
  • And, as I understand it, using this method I can get a specific properties or keys inside of an object and how to retrieve a specific object (if there are multiple objects in JSON file)? – Rumata Sep 04 '16 at 17:51
1

Basically, JSON is a structured format recently uses which would be preferred due to some advantages via developers, Like simpler and easier structure and etc. Ajax is not a language, It's a technique that you can simply send a request to an API service and update your view partially without reloading the entire page.

So you need to make a server-client architecture. In this case all your server-side responses would be sent in JSON format as RESTful API. Also you can simply use the JSON response without any conversion or something else like an array object in JavaScript.

You can see some examples here to figure out better: JSON example

halfer
  • 19,824
  • 17
  • 99
  • 186
Ramin Esfahani
  • 190
  • 1
  • 6
  • Thank you very much, but so far, I do not fully understand how it works. Do you know examples to explain from scratch, what code should be in what file? I found this example: http://www.tutorialsavvy.com/2013/10/using-handlebar-template-for-json-response.html/#prettyPhoto But the downloaded version does not work. – Rumata Aug 21 '16 at 15:27
  • You can download it in this page: https://docs.google.com/file/d/0B2Iq42FA1tljZUdHOXNzQlpMc3M/edit – Ramin Esfahani Aug 21 '16 at 22:08
  • Yes, thank you, but when I open handlebar-template-test I can't see anything except a small gray line. – Rumata Aug 21 '16 at 23:09