如下爲js代碼:html
var header = document.querySelector('header'); var section = document.querySelector('section'); var requestURL = 'https://raw.githubusercontent.com/PLAYERYENNEY/QIMO/master/shikigami.json'; //新建對象 var request = new XMLHttpRequest(); //初始化請求 request.open('GET', requestURL); request.responseType = 'json'; request.send(); //規定請求響應類型 request.onload = function () { var superHeroes = request.response; populateHeader(superHeroes); showHeroes(superHeroes); } //匿名函數,把響應回來的值賦給變量,而後調用函數 function populateHeader(jsonObj) { var myH1 = document.createElement('h1'); myH1.textContent = jsonObj['squadName']; header.appendChild(myH1); var myPara = document.createElement('p'); myPara.textContent = '輸出 / ' + jsonObj['homeTown'] + ' / 輔助 / ' + jsonObj['formed']; header.appendChild(myPara); } //對象建立對象(節點)myH1,賦值,放入header成爲子對象 function showHeroes(jsonObj) { var heroes = jsonObj['members']; for (var i = 0; i < heroes.length; i++) { var myArticle = document.createElement('article'); var myH2 = document.createElement('h2'); var myPara1 = document.createElement('p'); var myPara2 = document.createElement('p'); var myPara3 = document.createElement('p'); var myList = document.createElement('ul'); myH2.textContent = heroes[i].name; myPara1.textContent = 'TYPE: ' + heroes[i].secretIdentity; myPara2.textContent = 'HOW: ' + heroes[i].age; myPara3.textContent = 'EG:'; var superPowers = heroes[i].powers; for (var j = 0; j < superPowers.length; j++) { var listItem = document.createElement('li'); listItem.textContent = superPowers[j]; myList.appendChild(listItem); } myArticle.appendChild(myH2); myArticle.appendChild(myPara1); myArticle.appendChild(myPara2); myArticle.appendChild(myPara3); myArticle.appendChild(myList); section.appendChild(myArticle); } } //聲明變量數組1 heroes並賦值members,數組2 superpowers並賦值
上傳到github文件地址爲:https://github.com/PLAYERYENNEY/QIMO/blob/master/shikigami.jsongit
代碼以下:github
{ "squadName" : "SHIKIGAMI", "homeTown" : "控制", "formed" : "治療" , "secretBase" : "Super tower", "active" : true, "members" : [ { "name" : "輸出", "age" : "對敵方形成傷害", "secretIdentity" : "主要屬性堆積:暴擊,暴傷,攻擊", "powers" : [ "荒 / SUSABI", "大天狗 / OOTENGU", "茨木童子 / LBARAKI DOJI" ] }, { "name" : "控制", "age" : "對敵方形成混亂,沉默等控制效果", "secretIdentity" : "主要屬性堆積:效果命中,速度", "powers" : [ "閻魔 / ENMA", "雪女 / YUKI ONNA", "兵俑 / SAMURAI X" ] }, { "name" : "輔助", "age" : "對己方增強狀態或者爲己方增長護盾", "secretIdentity" : "主要屬性堆積:暴擊,生命,暴傷", "powers" : [ "輝夜姬 / KAGUYA", "一目連 / LCHIMOKUREN", "追月神 / OITSUKI" ] }, { "name" : "治療", "age" : "爲己方回覆生命", "secretIdentity" : "主要屬性堆積:生命,暴擊,暴傷", "powers" : [ "花鳥卷 / HANA", "桃花妖 / MOMO", "櫻花妖 / SAKURA" ] } ] }
運行效果詳情於期末項目3.0版本,具體爲shikigami.htmljson