我如何使HTML使用句柄来填充JSON文件中的内容? [英] How can I make HTML fill itself with the content from the JSON file using handlebars?

查看:187
本文介绍了我如何使HTML使用句柄来填充JSON文件中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用胡子或句柄让JSON文件中的内容填充本身。 我创建了两个简单的 HTML模板进行测试(使用句柄),并使用来自外部 Javascript文件的内容填充它们。 http://codepen.io/MaxVelichkin/pen/qNgxpB



现在我需要将内容初始化为 JSON文件



我遇到了两个问题,但它们都是位于同一主要问题的解决方案的核心 - 在JSON文件和HTML 中创建内容之间的链接,因此我决定在同一问题中询问他们。



(如果您认为有必要单独提出这些问题,请回答其中一个问题,我将删除第二个问题并单独提出。)







  1. 如何连接 JSON HTML ?据我所知,有一种方法,使用 AJAX ,并且有一种方法使用服务器 AJAX 对我来说是一种新语言,因此我非常感谢我使用节点创建的使用本地HTTP服务器的解释.JS

  2. JSON文件中的语法应该是什么? JSON文件中的脚本必须与 Javascript文件中的脚本相同,但应该在 JSON的帮助下处理。解析函数,是否正确?或 JSON文件中的语法应该不同?

    例如,如果我们考虑我的示例(上面的链接), JSON文件必须与 Javascript文件中的相同,但在最后一行 document.getElementById('quoteData')。innerHTML + = quoteData; ,我必须写下面的行 var contentJS = JSON.parse(quoteData); ,然后在最后一行更改变量的名称,所以它会be: document.getElementById('quoteData')。innerHTML + = contentJS; ,是对吗?


解决方案

试试这个:
$ b HTML:

 <! -  template-1  - > 
< div id =testData>< / div>
< script id =date-templatetype =text / x-handlebars-template>
日期:< span> < b取代; {{日期}}< / B个< /跨度> <峰; br />时间:< span>< b> {{time}}< / b>< / span>
< / script>

JS:

  function sendGet(callback){
/ *使用XMLHttpRequest * / $ b $创建AJAX请求var xhr = new XMLHttpRequest();
/ *参考json网址:http://www.jsontest.com/*/

/ *使用XMLHttpRequestopen,
指定请求的类型这里的'GET'(参数一)引用请求类型
http://date.jsontest.com/(参数二)引用JSON文件位置* /
xhr.open('GET' ,http://date.jsontest.com/);

使用onload事件处理函数可以检查请求的状态* /
xhr.onload = function(){
if(xhr.status === 200){
回调(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};

*使用onerror事件处理函数可以检查错误状态,如果你的请求未能获得数据* /
xhr.onerror = function(){
alert(Network错误);
};

/ *将请求发送到服务器* /
xhr.send();
}

//对于模板-1
var dateTemplate = document.getElementById(date-template)。innerHTML;
var template = Handlebars.compile(dateTemplate);
$ b sendGet(function(response){
document.getElementById('testData')。innerHTML + = template(response);
})

JSON

JSON数据格式来源于JavaScript,所以它看起来更像JavaScript对象,Douglas Crockford最初指定了JSON格式,请检查 here

JavaScript Object Notation有一套规则。

$ {
$ b


  1. 从大括号({)开始,以大括号括起来}}
    ex:{}


  2. 你可以添加'key'和它的'value'如{title:hello json}
    这里title是关键字, hello json是该键的值。

  3. key应该是字符串


  4. 价值可以是:

    数字

    string

    布尔值

    array

    object


  5. 不能在里面添加JavaScript注释JSON(如//或/ ** /)

有许多在线的JSON验证器,您可以检查您的JSON有效或无效,请查看此处






当涉及到将JSON链接到js文件时,它更像是提供一个接口来获取JSON数据并将其用于JavaScript。



这里是XMLHttpRequest我们的界面。我们通常调用XMLHttpRequest API。

在给定的js代码中,使用REST API从服务器获取JSON( http://date.jsontest.com/

有关REST API的更多信息,您可以查看此处



来自网址: http://date.jsontest.com/ 你可以得到像下面这样的JSON对象。 />

  {
time:03:47:36 PM,
milliseconds_since_epoch :1471794456318,
date:08-21-2016
}
注意:数据是动态的;每个请求的值都会更改。

因此,通过使用外部API,您可以获得JSON,以便在您的JavaScript文件/代码库中使用它需要将JSON转换为JavaScript对象

JSON.parse(/ *你的JSON对象在这里* /)将JSON转换为js Object


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


。b $ b

通过使用点(。)或括号([])表示法,您可以访问JavaScript Object属性或键;

  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 [ (响应对象[日期])// // 1471794456318

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

因此,要链接本地JSON文件(从本地目录)或外部您可以在JavaScript文件中使用API​​XMLHttpRequest。

'sendGet'函数已在上述js块中更新,并带有注释请检查。



以简单的方式: p>


  1. 创建XMLHttpRequest实例<
    例如:var xhr = new XMLHttpRequest();

  2. 打开请求类型

    例如:xhr.open('GET',http:/ /date.jsontest.com /);

  3. 发送GET请求到服务器

    ex:xhr.send();

  4. 如果响应的状态码为200,则注册装载事件处理程序以保存JSON对象。 $ b 例如:xhr.onload = function(){

信息检查此处





$ b

了解以下内容:


  • 对象文字表示法

  • 原始数据类型与非原始数据类型之间的区别


    现有引用:


    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?

    解决方案

    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:

    这篇关于我如何使HTML使用句柄来填充JSON文件中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆