How can I make HTML fill itself with the content from the JSON file using handlebars?

谁说胖子不能爱 提交于 2019-12-04 20:44:38
Naresh Seepana

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:

Basically, JSON is a structured format recently uses which would be prefered 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 RESTFULL 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

Hope this can help you. Regards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!