html获取网络数据,列表展示 第二种
js遍历json数组中的json对象
image.png
|| '-' 判断数据是否为空,为空就显示 -
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>网页列表</title>
<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);
var imgurlStr = "";
// // 打印,获取json里的对象
var data2 = JSON.parse(xhr.responseText);
data2.forEach(item => {
imgurlStr += `
<div id="${item.id}">
<div>${item.id}</div>
<img style="width: 100px; height: 100px;" src="${item.url}" alt="" width=" ${item.width}px" height="${item.height}px">
</div>
`
})
document.getElementById("listID").innerHTML = imgurlStr;
}
};
</script>
</head>
<body>
<div id="listID"> </div>
</body>
</html>
或这样
image.png
data2.forEach((item, index) => {
imgurlStr += `
<div id="${item.aJZT}-${index}" style="margin-bottom:20px;border-radius:10px;border:1px solid #ddd;">
<div style="border: 1px #f2f2f2 double; margin: 12px;">
<div class="cell2" style="font-weight:bold;font-size:30px;">
<div class="cell-lab">某某时间</div>
<div class="cell-val" id="cXSJ">${item.cXSJ|| '-'}</div>
</div>
<div class="cell">
<div class=" cell-lab">某某状态</div>
<div class="cell-val" id="aJZT">${item.aJZT || '-'}</div>
</div>
</div>
</div>
`
})