解析JSON对象后,如何使用普通的RESTful JavaScript显示从JSON API调用返回的数据?
我是用数据创建HTML元素并将它们添加到页面中,还是有隐藏的HTML元素并对返回的数据进行innerHTML,然后通过CSS显示这些元素?
发布于 2016-09-09 23:46:06
我决定了我所需要的最好的方法是在我的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 I:
/**
* 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);https://stackoverflow.com/questions/34913812
复制相似问题