首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用RESTful API调用JavaScript显示返回的JSON

如何用RESTful API调用JavaScript显示返回的JSON
EN

Stack Overflow用户
提问于 2016-01-21 01:28:33
回答 1查看 925关注 0票数 0

解析JSON对象后,如何使用普通的RESTful JavaScript显示从JSON API调用返回的数据?

我是用数据创建HTML元素并将它们添加到页面中,还是有隐藏的HTML元素并对返回的数据进行innerHTML,然后通过CSS显示这些元素?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-09 23:46:06

我决定了我所需要的最好的方法是在我的html底部创建一个HTML模板。这样,我就可以减少必须手动编写的DOM元素的数量:

代码语言:javascript
复制
<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:

  1. 缓存模板,
  2. 创建一个DOM元素来注入模板
  3. 插入数据
  4. 然后将模板附加到DOM中。
代码语言: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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34913812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档