为什么剩下的api电话不起作用?

时间:2017-09-18 12:14:26

标签: javascript api http

我试图通过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);
    }

2 个答案:

答案 0 :(得分:1)

以下是示例代码。此代码工作正常。

<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>

答案 1 :(得分:1)

您获取数据的方法有点陈旧,最近所有主流浏览器都支持fetch api

您可以像以下一样使用它:

fetch('https://newsapi.org/v1/articles?source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58')
  .then(r => r.json())
  .then(data => {
    document.getElementById("root").innerText = JSON.stringify(data, 0, 2)
  })
<pre id="root">
</pre>