gpt4 book ai didi

javascript - 如何显示JSON的每个值

转载 作者:行者123 更新时间:2023-11-28 14:11:54 24 4
gpt4 key购买 nike

<script>

alert('sorry this code snipprt was done by mistake ');

</script>
<!DOCTYPE html>
<html>
<head>
<title>News</title>
</head>
<body>
sorry this code snippet was done by mistake
</body>

</html>

<script>

alert('sorry this code snipprt was done by mistake ');

</script>
<!DOCTYPE html>
<html>
<head>
<title>News</title>
</head>
<body>
sorry this code snippet was done by mistake
</body>

</html>

我正在通过 URL 使用新闻 API:https://newsapi.org/v2/top-headlines?sources=google-news-in&apiKey=xxxxxxxxxxxxxxxx ,我正在使用 Javascript 中的查询来解码 JSON

我期待这个结果如图所示 expecting image

我已经尝试过这段代码

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<script>

var c = 'https://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

function myFun() {

var yt = '';
$.ajax({
url: c,
dataType: 'json',
type:'get',
cache: false,
success: function(data) {

var art = data;

var source = art.articles;

var i;

for (var i = 0; i < source.length; i++) {
var x = art.articles[i];

document.getElementById('result').innerHTML = '<style type=text/css>button{border-radius:16px;background-color:white;border:1px solid black;font-size:15px;fontalign:center;cursor:pointer;position:relative;height:16%;width:flex-start;display:inline-flex;itemalign:center;} img{border-top-left-radius: 16px;border-bottom-left-radius:16px;} h3{font-size:38px;width:flex-start;height:flex-start;} </style> <div><li><a href="'+x.url+'"><button><center><img src="'+x.urlToImage+'" height="247px" width="480px"></center><h3>'+x.title+'</h3></button></a><br><br><br></li></div>';
}

}
});

}

</script>
<!DOCTYPE html>
<html>
<head>
<title>News</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body onload="myFun();">

<div id="result"></div>
</body>
</html>

但此代码仅显示 JSON 的最后一个值,并且所有值都会被跳过,如图所示 result image

最佳答案

实际上,每次使用 id="result"的 div 内容都会被覆盖尝试修改代码如下:

document.getElementById('result').innerHTML += ...

注意+=

关于javascript - 如何显示JSON的每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com