There is a function that sends an Ajax request to the JSON file for content, parses it, compiles it with the Handlebars Template, and places it in the desired div on the html page. How to “teach” it not to take the entire content of the JSON file, but only a specific object / array or element of an object / array (so that you can then replace this part of the code with a variable that you set when calling a function)
Ajax and XMLHttpRequest just started to learn, I will be glad to advice.
Here is the function (framed as commonjs module):
module.exports = function(jsonDir, templId, finId){ function sendGet(callback) { /* create an AJAX request using XMLHttpRequest*/ var xhr = new XMLHttpRequest(); /* Specify the type of request by using XMLHttpRequest "open", here 'GET'(argument one) refers to request type "jsonDir" (argument two) refers to JSON file location*/ xhr.open('GET', jsonDir); /*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(templId).innerHTML; var template = Handlebars.compile(dateTemplate); sendGet(function (response) { document.getElementById(finId).innerHTML += template(response); }) }
JSON.parse(xhr.responseText)). - Andrew BJSON.parse(xhr.responseText))xhr variable stores JSON content in JS format and Now you can refer, for example, to the desired object or array viaxhr.objectName.propertyName? - Rumatavar resp = JSON.parse(response);You get a ready object that you can work with as with any other js objectvar x = resp.setting1 || "default";var x = resp.setting1 || "default";- Andrew Bпустая строка, null, undefined, 0, falsewill not pass it (the string after||will be used instead). This is not a very good way because of the features, but short. - Andrew B