0
解析JSON对象后,如何使用vanilla JavaScript显示从RESTful API调用返回的数据?如何使用JavaScript显示从RESTful API调用返回的JSON
是否使用数据创建HTML元素并将它们添加到页面或者是否隐藏了HTML元素和innerHTML返回的数据然后通过CSS显示元素?
解析JSON对象后,如何使用vanilla JavaScript显示从RESTful API调用返回的数据?如何使用JavaScript显示从RESTful API调用返回的JSON
是否使用数据创建HTML元素并将它们添加到页面或者是否隐藏了HTML元素和innerHTML返回的数据然后通过CSS显示元素?
我决定为我所需要的最好的方法是在我的html底部创建一个HTML模板。这样,我可以减少DOM元素的数量我将不得不手动代码:
<script id="daily-template" type="text/template">
<div class="xl-12">
<h2 class="location"><?php echo $daily['name']; ?>, <?php echo $daily['sys']['country']; ?></h2>
<img class="flag" />
</div>
<div class="xl-2 s-12 m-6 no-padding-top h140 text-center">
<h3 class="description"></h3>
<img class="icon" />
</div>
<div class="xl-2 s-12 m-6 no-padding-top h140 text-center">
<h5>Current</h5>
<h5 class="temp"></h5>
</div>
<div class="xl-2 s-6 m-3 text-center">
<h5>Low</h5>
<h5 class="min-temp"></h5>
</div>
<div class="xl-2 s-6 m-3 text-center">
<h5>High</h5>
<h5 class="max-temp"></h5>
</div>
<div class="xl-2 s-6 m-3 text-center">
<h5>Humidity</h5>
<h5 class="humidity"></h5>
</div>
<div class="xl-2 s-6 m-3 text-center">
<h5>Wind</h5>
<h5 class="wind"></h5>
</div>
<div class="clear"></div>
</script>
然后使用一些有创意的Javascript我:
/**
* Display the results from API call
*/
// get the template
var dailyTemplate = document.getElementById('daily-template').innerHTML,
// create an element to inject the template
dailySite = document.createElement('div');
// inject the template
dailySite.innerHTML = dailyTemplate;
/**
* Inject the data to the template
*/
// location
dailySite.getElementsByClassName('location')[0].innerHTML = current.name + ', ' + current.sys.country;
// flag
dailySite.getElementsByClassName('flag')[0].src = 'http://openweathermap.org/images/flags/' + current.sys.country.toLowerCase() + '.png';
// description
dailySite.getElementsByClassName('description')[0].innerHTML = ucfirst(current.weather[0].description);
// weather icon
dailySite.getElementsByClassName('icon')[0].src = 'http://openweathermap.org/img/w/' + current.weather[0].icon + '.png';
// all other code omitted...
// append the template to the DOM
document.getElementById("search-results").appendChild(dailySite);
这完全取决于您 - 这是一个设计选择。一旦您获得了javascript对象所需的数据,您就可以随心所欲地执行任何操作。 –
感谢尼克,但您认为最好的方法是什么? –
您能否提供更多见解来了解您想要完成的任务? –