我正在尝试通过api调用来获取数据,但是浏览器始终显示xhr加载失败。我无法理解我的代码中的错误。
function letsgo()
{
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','https://newsapi.org/v1/articles?source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58',true);
ourRequest.onload = function()
{
if (ourRequest.status >= 200 && ourRequest.status < 400)
{
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
}
else
{
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
下面是记录数据的功能
function renderHTML(data) {
console.log(data);
}
最佳答案
这是示例代码。此代码工作正常。
<html>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<body>
<script>
$(document).ready(function () {
function renderHTML(data) {
console.log(data);
}
function letsgo() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',
'https://newsapi.org/v1/articles?
source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58',
true);
ourRequest.onload = function () {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned
an error.");
}
};
ourRequest.onerror = function () {
console.log("Connection error");
};
ourRequest.send();
}
letsgo();
})
</script>
</body>
</html>