将响应结果存储在变量中

时间:2018-02-09 18:31:36

标签: javascript html arrays api

我正在尝试学习如何使用newsapi.org api功能来引人注目并将它们放在我的网站上。我有自己的功能,我已经在Chrome控制台中进行了测试,它运行正常,但我无法弄清楚如何从阵列中访问结果。这是功能:

function pullNews() {    
var url = 'https://newsapi.org/v2/top-headlines?' +
          'country=ca&' +
          'apiKey=b96fda738da54749986d258f6d5f9682';
var req = new Request(url);
fetch(req)
    .then(function(response) {
        console.log(response.json());
    })    
}

我更愿意自己学习这个,所以如果有人能指出我正确的方向,甚至可能是正确的搜索词,我会非常感激。

2 个答案:

答案 0 :(得分:2)

json返回的响应上的方法fetch返回Promise,您将成为控制台日志记录。 要查看实际结果,您需要等到该承诺得到解决:

function pullNews() {
    var url = 'https://newsapi.org/v2/top-headlines?' +
            'country=ca&' +
            'apiKey=b96fda738da54749986d258f6d5f9682';

    var req = new Request(url);

    fetch(req)
        .then(function(response) {
            return response.json(); // this is another promise that needs resolving
        })
        .then(function(json) {
            console.log(json);
        })
}

使用async / await

有点整洁
async function pullNews() {
    const url = 'https://newsapi.org/v2/top-headlines?' +
                'country=ca&' +
                'apiKey=b96fda738da54749986d258f6d5f9682';

    var req = new Request(url);
    const response = await fetch(req);
    return response.json();
}

(async function() {
    const result = await pullNews();
    console.log(result);
})();

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<body>

<h2>Pure javascript</h2>

<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>

<script>
function loadXMLDoc() {
var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=ca&' +
      'apiKey=b96fda738da54749986d258f6d5f9682'
 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {

  console.log(JSON.parse(this.responseText));
  }
 };
xhttp.open("GET",url , true);
xhttp.send();
}
</script>
</body>
</html>

-------------------- JQuery的---------------

var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=ca&' +
      'apiKey=b96fda738da54749986d258f6d5f9682'
$.getJSON(url,function(data){console.log(data)})

--------------请求对象--------------

var req = new Request(url);
fetch(req).then(function(response) {return response.json();})
    .then(function(json) {
        console.log(json);
    });