运用json文件传输数据

时间:2022-10-16 19:33:03

可以自己先编写一个随意的测试的Html文件

接下来的js解析json代码如下:

<script type="text/javascript">
var header = document.querySelector('header');
var section = document.querySelector('section');
var requestURL = 'https://wxflal.github.io/study/filmname.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var file = request.response;
showone(file);
showtwo(file);
}

function showone(jsonObj) {
var myH1 = document.createElement('h1');
myH1.textContent = jsonObj['squadName'];
header.appendChild(myH1);
var myPara = document.createElement('p');
myPara.textContent = 'editor:' + jsonObj['editor'] + ' // hometown: ' + jsonObj['hometown'] + ' // active:' + jsonObj['active'];
header.appendChild(myPara);
}

function showtwo(jsonObj){
var filemembers = jsonObj['films'];

for (var i = 0; i < filemembers.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 = filemembers[i].name;
myPara1.textContent = 'time: ' + filemembers[i].time;
myPara2.textContent = 'writer: ' + filemembers[i].writer;
myPara3.textContent = 'moral:';

var moral = filemembers[i].moral;
for (var j = 0; j < moral.length; j++) {
var listItem = document.createElement('li');
listItem.textContent = moral[j];
myList.appendChild(listItem);
}

myArticle.appendChild(myH2);
myArticle.appendChild(myPara1);
myArticle.appendChild(myPara2);
myArticle.appendChild(myPara3);
myArticle.appendChild(myList);

section.appendChild(myArticle);
}
}

</script>

 

json代码地址:https://wxflal.github.io/study/filmname.json

运行结果尚未进行css布局,只用于测试解析json文件的js代码,显示解析数据结果而已