简体   繁体   中英

How do I call an API when a website page loads?

I need some help. So, I want to call this API and display the file given by it on my website

this is the link:

https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98

It generates this:

{
  "download_link": "http://ogramcloud.com/static/files/Fly_Me_to_the_Moon_Evangelion_OST.mp3", 
  "file_key": "061b78fb83ee928748b78bc7ee9f3e98", 
  "message": "file restored successfully !", 
  "status": "success"
}

I need to call this and display the http://ogramcloud.com/static/files/Fly_Me_to_the_Moon_Evangelion_OST.mp3 as a <audio> on my website.

how would I go to do that?

You can use jQuery to do that:

$(function () {
  $.get("https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98", function (response) {
    link = JSON.parse(response).download_link
    // append a <source> to your <audio> or do whatever you want with the link
  })
})

Here is the working solution using js fetch api.

 var audioLink; var audio = document.getElementById("audio"); var audioSource = document.getElementById("audioSource"); fetch("https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98").then(response => response.json()).then(data => { audioSource.src = data.download_link; audio.load(); audio.play(); });
 <audio id="audio" controls="controls"> <source id="audioSource" src=""></source> Your browser does not support the audio format. </audio>

Using the fetch api or XMLHttpRequest, you can make a request to your api.

Add an id to the audio in the HTML.

 let audio = document.getElementById("audio"); fetch("https://ogramcloud.com/api/download/061b78fb83ee928748b78bc7ee9f3e98").then(response => response.json()).then(data => { audio.src = data.download_link; audio.load(); audio.play(); });
 <audio controls="controls" src="" id="audio"> Your browser does not support the HTML5 Audio element. </audio>

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