简体   繁体   English

从API请求数据时获取“未定义”

[英]Getting 'undefined' when requesting data from API

Why am I getting 'undefined' when trying to pull specific data from Public API? 尝试从Public API中提取特定数据时,为什么会得到“未定义”? What is wrong with below code? 下面的代码有什么问题?

<body>
<button type="button" onclick="gget();">Click</button>
<p id="MyDiv"> </p> </body>

<script>function gget(){
   var btc = new XMLHttpRequest();
   btc.open('GET', "https://api.coinmarketcap.com/v1/ticker/bitcoin/", true);
   btc.onreadystatechange = function() {
       if(btc.readyState == 4) {
          var data = JSON.parse(btc.responseText);
          var price = data.id;
          document.getElementById('MyDiv').innerHTML = "$"+price;
    }};
    btc.send();
    } </script>

https://api.coinmarketcap.com/v1/ticker/bitcoin/ returns an array containing 1 object. https://api.coinmarketcap.com/v1/ticker/bitcoin/返回包含1个对象的数组。

You want to access data[0].id to access the ID of that first/only element. 您要访问data[0].id以访问该第一个/唯一元素的ID。 Price you're looking for is probably data[0].price_usd . 您正在寻找的价格可能是data[0].price_usd

To add to Jeto's answer, the code would look something like this, assuming you want the price in US dollars. 为了增加Jeto的答案,假定您想要美元价格,代码看起来像这样。

function gget(){
  var btc = new XMLHttpRequest();
  btc.open('GET', "https://api.coinmarketcap.com/v1/ticker/bitcoin/", true);
  btc.onreadystatechange = function() {
    if(btc.readyState == 4) {

      var data = JSON.parse(btc.responseText);
      var price = data[0].price_usd;
      document.getElementById('MyDiv').innerHTML = "$"+price;
    }};
  btc.send();
}

In addition, you can provide feedback to the user in error cases. 另外,您可以在错误情况下向用户提供反馈。

function setPriceLabel(value){
  document.getElementById('MyDiv').innerHTML = value;
}

function gget(){
  var btc = new XMLHttpRequest();
  btc.addEventListener("error", function(){
    setPriceLabel("Could not fetch price from server");
  });
  btc.open('GET', "https://api.coinmarketcap.com/v1/ticker/bitcoin/", true);
  btc.onreadystatechange = function() {
    if(btc.readyState == 4) {
        try{
          var data = JSON.parse(btc.responseText);
          console.log(data)
          var price = data[0].price_usd;
          setPriceLabel("$"+price);
        }
        catch(e){
          setPriceLabel("Server sent bad data");
        }
    }};
  btc.send();
}

The btc.addEventListener block will catch HTTP errors and set the price label to an error message. btc.addEventListener块将捕获HTTP错误并将价格标签设置为错误消息。

In addition to HTTP errors, it is also possible for the JSON parse function to fail. 除了HTTP错误外,JSON解析功能也有可能失败。 Since JSON.parse is a synchronous function, we can handle its errors with try-catch syntax. 由于JSON.parse是同步函数,因此我们可以使用try-catch语法处理其错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM