Home > Blockchain >  how to show youtube video in an html page with value received via json
how to show youtube video in an html page with value received via json

Time:12-31

I would like your help. I have to insert a youtube video whose url is received via json; in particular with

document.getElementById("idframe").innerHTML=myJson.Items[4].value;

I get https://youtu.be/ILmvKC-H1l0

So far everything ok. To insert the youtube video in an html page I was following this tutorial.

I just can't get what I want. I get a gray box with the words: It may have been moved, changed, or deleted. Can you kindly help me?

<html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style></style>
    </head>
    <body>

    <div>
<div > <iframe id="idframe" width="420" height="345" src="myFunction()"> </iframe> </div> <br>

    <br>

    <script>

    function myFunction() {
      var xmlhttp = new XMLHttpRequest();
    var url = "https://vnwcn9gt89.execute-api.us-east-2.amazonaws.com/book"; 
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
       var myJson = JSON.parse(this.responseText);
       document.getElementById("idframe").innerHTML = myJson.Items[4].value;
      }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    }

    </script>


    </body>
    </html> 

CodePudding user response:

Couple of changes required in your code:

  1. You cannot use shortened URL services like https://youtu.be/. Your url should be https://youtube.com/embed/ILmvKC-H1l0

  2. innerHTML won't work for iframe. Try below solution

(function() {
  //var xmlhttp = new XMLHttpRequest();
  var url = "https://vnwcn9gt89.execute-api.us-east-2.amazonaws.com/book";
  /*xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myJson = JSON.parse(this.responseText);
      //Your response for myJson.Items[4].value, should be equal to "https://youtube.com/embed/ILmvKC-H1l0"
      let youtubeUrl = myJson.Items[4].value;
      document.getElementById("idframe").src = youtubeUrl;
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();*/
  
  //consider incase you have youtubeUrl as " youtu.be/ILmvKC-H1l0";
  //Extract the id and append it like below
  let returnedYoutubeUrl = "https://youtu.be/ILmvKC-H1l0";
  let id = returnedYoutubeUrl.split("/")[3];
  console.log(id);
  document.getElementById("idframe").src = "https://youtube.com/embed/" id;
})();
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style></style>
</head>

<body>
  <div>
    <div >
      <iframe id="idframe" width="420" height="345"> </iframe>
    </div>
  </div>
</body>

</html>

  • Related