×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Gary Peach
Added: Nov 28, 2017 2:59 PM
Modified: Nov 28, 2017 3:01 PM
Views: 1
ajax call from api - weather
  1. <body>
  2.  
  3.       <header>
  4.  
  5.       </header>
  6.  
  7.       <section>
  8.  
  9.       </section>
  10.  
  11.     <script>
  12.     var header = document.querySelector('header');
  13.     var section = document.querySelector('section');
  14.  
  15.     var requestURL = 'https://gist.githubusercontent.com/ErnieAtLYD/a8c4126ecf954a4136c128aca33881e4/raw/47988536cdcbfd45af5727f5f1214d7b498e966e/weather-feed.json';
  16.     var request = new XMLHttpRequest();
  17.     request.open('GET', requestURL);
  18.     request.responseType = 'json';
  19.     request.send();
  20.     console.log('called');
  21.  
  22.     request.onload = function() {
  23.    
  24.       var weather = request.response;
  25.       populateHeader(weather);
  26.       showWeather(weather);
  27.     }
  28.  
  29.     function populateHeader(jsonObj) {
  30.       var myH1 = document.createElement('h1');
  31.       myH1.textContent = 'cod: ' + jsonObj['cod'];
  32.       header.appendChild(myH1);
  33.  
  34.       var myPara = document.createElement('p');
  35.       //myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
  36.       //header.appendChild(myPara);
  37.  
  38.     }
  39.  
  40.     function showWeather(jsonObj) {
  41.       var list = jsonObj['list'];
  42.       for(var i = 0; i < list.length; i++) {
  43.       //alert(list[i].coord.lon);
  44.         var myArticle = document.createElement('article');
  45.         var myH2 = document.createElement('h2');
  46.         var myPara1 = document.createElement('p');
  47.         var myPara2 = document.createElement('p');
  48.         var myPara3 = document.createElement('p');
  49.         var myList = document.createElement('ul');
  50.  
  51.         myH2.textContent = list[i].name;
  52.         myPara1.textContent = 'lat: ' + list[i].coord.lat;
  53.         myPara2.textContent = 'lon: ' + list[i].coord.lon;
  54.  
  55.         myArticle.appendChild(myH2);
  56.         myArticle.appendChild(myPara1);
  57.         myArticle.appendChild(myPara2);
  58.         myArticle.appendChild(myList);
  59.  
  60.         section.appendChild(myArticle);
  61.       }
  62.     }
  63.  
  64.     </script>
  65.   </body>