因此,我刚开始使用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=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>
它通过.getJSON调用获取一些数据,然后在单击按钮时尝试呈现该数据。没有数据正在渲染。有人可以告诉我我在做什么错吗?
请查看此URL以查看返回的数据https://restcountries.eu/rest/v2/name/aruba?fullText=true的结构
最佳答案
该API返回一个JSON数组,而不是一个对象,这就是它不起作用的原因。
如果只想要第一项,则可以执行以下操作:
var template = $("#mp_template").html();
var text = Mustache.render(template, data[0]);
console.log(data);
$("#mypanel").html(text);
或者,您也可以通过在对象属性中传递数组来遍历所有国家/地区:
{ countries: data }
并在模板中使用{{#countries}}
$(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, { countries: data });
$("#mypanel").html(text);
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<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">
{{#countries}}
<p>Country: {{ name }}</p>
<p>Capital: {{ capital }}</p>
<p>Flag: <img src={{{ flag }}} style="width: 50px"></p>
{{/countries}}
</script>
<div id="mypanel"></div>
<button id="btn">Load</button>
</body>