Ad

How Do I Display Returned JSON From RESTful API Call With JavaScript

After parsing a JSON object, how do I display the returned data from a RESTful API call with vanilla JavaScript?

Do I create HTML elements with the data and add them to the page or do I have hidden HTML elements and innerHTML the returned data then display the elements via CSS?

Ad

Answer

I decided the best approach for what I needed was to create an HTML template at the bottom of my html. This way I could reduce the number of DOM elements I would have to manually code:

<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>

Then using some creative Javascript I:

  1. cache the template,
  2. create a DOM element to inject the template
  3. insert the data
  4. and then append the template to the DOM

/**
 * 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);
Ad
source: stackoverflow.com
Ad