Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Mustache不呈现JSON数据_Javascript_Jquery_Mustache - Fatal编程技术网

Javascript Mustache不呈现JSON数据

Javascript Mustache不呈现JSON数据,javascript,jquery,mustache,Javascript,Jquery,Mustache,所以,我刚开始用小胡子JS。我有一个简单的html文件 <!DOCTYPE html> <html lang="en"> <head> <title>JavaScript Mustache template</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale

所以,我刚开始用小胡子JS。我有一个简单的html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JavaScript Mustache template</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
</head>

<body>
    <script id="mp_template" type="text/template">
        <p>Country: {{ name }}</p>
        <p>Capital: {{ capital }}</p>
        <p>Flag: <img src={{{ flag }}} ></p>
    </script>
    <div id="mypanel"></div>
    <button id="btn">Load</button>
    <script>
        $(function () {
            $("#btn").on('click', function () {
                $.getJSON('https://restcountries.eu/rest/v2/name/aruba?fullText=true', function (data) {
                    var template = $("#mp_template").html();
                    var text = Mustache.render(template, data);
                    console.log(data);
                    $("#mypanel").html(text);
                });
            });
        });
    </script>

JavaScript胡子模板
国家:{{name}

大写:{{Capital}

旗帜:

负载 $(函数(){ $(“#btn”)。在('click',函数(){ $.getJSON('https://restcountries.eu/rest/v2/name/aruba?fullText=true,函数(数据){ var template=$(“#mp_template”).html(); var text=Mustache.render(模板、数据); 控制台日志(数据); $(“#mypanel”).html(文本); }); }); });
它通过.getJSON调用获取一些数据,然后尝试在单击按钮时呈现这些数据。没有数据正在渲染。有人能告诉我我做错了什么吗


请查看此URL以查看返回数据的结构

API返回的是JSON数组,而不是对象,这就是它不起作用的原因

如果您只想要第一项,可以执行以下操作:

 var template = $("#mp_template").html();
 var text = Mustache.render(template, data[0]);
 console.log(data);
 $("#mypanel").html(text);
或者,您可以通过在对象属性中传递数组来遍历所有国家:
{countries:data}
并在模板中使用
{{{countries}

$(函数(){
$(“#btn”)。在('click',函数(){
$.getJSON('https://restcountries.eu/rest/v2/name/aruba?fullText=true,函数(数据){
var template=$(“#mp_template”).html();
var text=Mustache.render(模板,{countries:data});
$(“#mypanel”).html(文本);
});
});
});

{{{国家}
国家:{{name}

大写:{{Capital}

旗帜:

{{/国家} 负载
为了处理返回的数组中的每个对象,模板中需要一个循环@MarcosCasagrande。代码运行得很好。