html获取网络数据,列表展示
js遍历json数组中的json对象
image.png
|| '-' 判断数据是否为空,为空就显示 -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>网页列表</title>
</head>
<body>
<div>
<div style="width: 100px; height: 100px;" id="myDiv"></div>
</div>
<script type="text/javascript">
// https://api.thecatapi.com/v1/images/search?limit=2
//
// {
// "id": "1ep",
// "url": "https://cdn2.thecatapi.com/images/1ep.jpg",
// "width": 448,
// "height": 674
// },
// 创建XMLHttpRequest对象,新版本的浏览器可以直接创建XMLHttpRequest对象,IE5或IE6没有
// XMLHttpRequest对象,而是用的ActiveXObject对象
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject("microsoft.XMLHttp")
xhr.open("get", 'https://api.thecatapi.com/v1/images/search?limit=2', true);
xhr.send(); //发送请求
// 监听请求的状态
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功后的处理
console.log('111 111 返回的数据', xhr.responseText);
// // 打印,获取json里的对象
var data2 = JSON.parse(xhr.responseText);
let myDiv = document.getElementById("myDiv")
let myimg = document.getElementById("myimg")
for (var i = 0; i < data2.length; i++) {
console.log('ggg 000 返回的数据', data2[i].id + " " + data2[i].url);
let addImg = document.createElement('img')
addImg.src = data2[i].url
addImg.style.width = "200px";
addImg.style.height = "200px";
myDiv.append(addImg)
let addName = document.createElement('p')
addName.innerText = data2[i].id
myDiv.append(addName)
}
}
};
</script>
</body>
</html>