How can I make HTML fill itself with the content f

2019-04-17 11:40发布

I need to make HTML fill itself with content from JSON file using the 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.

(If you think that it is necessary to ask these questions separately, please answer one of the questions, I will remove the second and ask it separately.)


  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?

2条回答
Emotional °昔
2楼-- · 2019-04-17 11:55

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:

查看更多
做自己的国王
3楼-- · 2019-04-17 12:05

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.

查看更多
登录 后发表回答