我正在尝试创建聚合来自不同内容提供商的新闻的网页。我正在使用https://newsapi.org提供的API 。
我想检索提供者的名称并将其附加到列表中。
但是我做错了什么,无法理解什么,看来我没有发送 get 请求。
这是我的笨蛋
https://embed.plnkr.co/WKPPzmFGdrruuXzumog6/
和代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spotify Breakout</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function queryApi() {
$(document).ready(function() {
const searchURL = 'https://newsapi.org/v1/sources?language=en';
$.get(searchURL, {
type: 'sources',
key: '0dcb4145d12f4a129cad2c7cfa52a2b9'
}).done(function(data){
\ var names = data.sources.name;
names.forEach(function(names) {
var nameDiv = $('<li>');
nameDiv.html(sources.name);
$('#nameList').append(nameDiv);
});
});
});
}
</script>
</head>
<body>
<ul id="nameList"></ul>
</body>
</html>
最佳答案
您的代码从 API 获取数据。但是,您从 API 检索(解析)数据的方式是错误的。您最好在解析之前检查数据是如何构造的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spotify Breakout</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function() {
const searchURL = 'https://newsapi.org/v1/sources?language=en';
$.get(searchURL, {
type: 'sources',
key: '0dcb4145d12f4a129cad2c7cfa52a2b9'
}).done(function(data){
var names = data.sources.name;
data.sources.forEach(function(source) {
var nameDiv = $('<li>');
nameDiv.html(source.name);
$('#nameList').append(nameDiv);
});
});
});
</script>
</head>
<body>
<ul id="nameList"></ul>
</body>
</html>
关于JQuery 通过 API 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47508087/