简体   繁体   中英

Calling API with Javascript html

What is the correct way to call this API? The api url is: https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd

I tried with this code

<p id="demo">
 </p>
 <script>
  var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.bitcoin;
        }
    };
    xmlhttp.open("GET", "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" + new Date().getTime(), true);
    xmlhttp.send();
 </script>

however the value I get is [object Object]. I want to get the value in "usd".

Where am I wrong? Thx

Replaces myObj with myObj.usd but returns null value

The API returns in the form of {"bitcoin":{"usd": -insert value here-}} , so you have to use myObj.bitcoin.usd

You need to access the usd part of the object when you set the innerHTML as @SuspenseFallback mentioned.

You also need to remove the + new Date().getTime() part from your URL string. I don't see a date part in the API docs for the price endpoint.

you should use the fetch method. the better and the modern way of calling API using native javascript.

There is no problem with the way you did it but there are a few things that you can do with fetch and not with XHR.

you can read more about fetch by this link: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

there is an example of using fetch:

fetch(
  "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
)
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
  });

or you can use async-await to achieve the same result:

(async () => {
  const response = await fetch(
    "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
  );
  const data = await response.json();
  console.log(data);
})();

note: I have used Javascript Self Invoking Functions which is a function that calls itself.

The answers quickly resolve the issue, however I ran into another problem where there are hyphenated words.

Sample API: https://api.coingecko.com/api/v3/simple/price?ids=bitcoin-cash&vs_currencies=usd

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