【问题标题】:How do I call an API when a website page loads?网站页面加载时如何调用 API?
【发布时间】:2020-11-09 01:31:56
【问题描述】:

我需要一些帮助。 所以,我想调用这个 API 并在我的网站上显示它给出的文件

这是链接:

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

它会生成这个:

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

我需要调用它并在我的网站上将http://ogramcloud.com/static/files/Fly_Me_to_the_Moon_Evangelion_OST.mp3 显示为<audio>

我该怎么做呢?

【问题讨论】:

    标签: javascript html api dom frontend


    【解决方案1】:

    这是使用 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>

    【讨论】:

    • 谢谢!我可以为我可能需要的任何文件的图像执行此操作吗?
    • 是的,你应该能够做到这一点。
    • 太棒了!我希望你也不会介意投票!
    【解决方案2】:

    您可以使用jQuery 来做到这一点:

    $(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
      })
    })
    

    【讨论】:

      【解决方案3】:

      使用 fetch api 或 XMLHttpRequest,您可以向您的 api 发出请求。

      在 HTML 中的音频中添加 id

      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>

      【讨论】:

        猜你喜欢
        • 2020-10-22
        • 2012-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多