簡體   English   中英

為什么其余的api調用不起作用?

[英]why is the rest api call not working?

我正在嘗試通過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>

您的數據獲取方法有點陳舊,最近所有主流瀏覽器都支持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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM