2016-01-21 135 views
0

解析JSON對象後,如何使用vanilla JavaScript顯示從RESTful API調用返回的數據?如何使用JavaScript顯示從RESTful API調用返回的JSON

是否使用數據創建HTML元素並將它們添加到頁面或者是否隱藏了HTML元素和innerHTML返回的數據然後通過CSS顯示元素?

+0

這完全取決於您 - 這是一個設計選擇。一旦您獲得了javascript對象所需的數據,您就可以隨心所欲地執行任何操作。 –

+0

感謝尼克,但您認爲最好的方法是什麼? –

+0

您能否提供更多見解來了解您想要完成的任務? –

回答

0

我決定爲我所需要的最好的方法是在我的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我:

  1. 緩存中的模板,
  2. 創建一個DOM元素注入模板
  3. 插入數據
  4. ,然後在模板追加到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);