简体   繁体   中英

Getting 'undefined' when requesting data from API

Why am I getting 'undefined' when trying to pull specific data from 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.

You want to access data[0].id to access the ID of that first/only element. Price you're looking for is probably 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.

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.

In addition to HTTP errors, it is also possible for the JSON parse function to fail. Since JSON.parse is a synchronous function, we can handle its errors with try-catch syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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