2017年11月7日 星期二

Javascript - JSON筆記

透過XMLHttpRequest API 載入JSON

宣告XMLHttpRequest物件
var request = new XMLHttpRequest();

設定請求
request.open('GET', requestURL);

設定取得的格式
request.responseType = 'json';
request.send();

處理取得的JSON
request.onload = function() {
  var superHeroes = request.response;
  populateHeader(superHeroes);

}

function populateHeader(jsonObj) {
  var myH1 = document.createElement('h1');
  myH1.textContent = jsonObj['squadName'];
  header.appendChild(myH1);

  var myPara = document.createElement('p');
  myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
  header.appendChild(myPara);
}

參考資訊
https://www.fooish.com/jquery/dom-manipulation.html

沒有留言:

張貼留言