QuartsPy
QuartsPy

Reputation: 31

How would I make a div containing the image I got from an online json?

So I want to grab the link off of https://nekos.life/api/v2/img/meow and the image on my site. I saw on the official nekos main page that they put the image on the front without doing a script. So something like that would be nice. If you check on the site, it is in a small box, but I basically want that but full-screened so I can use the API easier.

If there is not enough detail, COMMENT PLEASE about the question.

Thanks!

Upvotes: 0

Views: 35

Answers (3)

QuartsPy
QuartsPy

Reputation: 31

I combined all of your into a shorter one! Thanks!

<script>
function Get(yourUrl){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET",yourUrl,false);
    Httpreq.send(null);
    return Httpreq.responseText;          
}
var div = document.getElementById('myImg');
var json = JSON.parse(Get("https://nekos.life/api/v2/img/meow"));
div.innerHTML = "<img src='"+json.url+"'/>";
</script>

Upvotes: 0

NetanMangal
NetanMangal

Reputation: 354

This should work

<html>
  <head>
    <title>
      Title of you site
    </title>
  </head>
  
  <body>
    <div>
       <img id="myImg" src="" alt="You can have other details added"></img>
    </div>
  </body>
  
  <script>
    let response = await fetch('https://nekos.life/api/v2/img/meow');
    let data = await response.json();
    document.getElementById("myImg").src = data.url;
  </script>
</html>

Upvotes: 1

cs641311
cs641311

Reputation: 308

<div id='container'></div> <!-- THIS DIV HOLDS THE IMAGE-->
<script>
var div = document.getElementById('container'); //change to actaul id of div on your site
var url = 'https://nekos.life/api/v2/img/meow'; //url of image
var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status, xhr.response);
      }
    };
  xhr.send();
};
getJSON(url, callback);
function callback(n, data) {
  div.innerHTML = "<img src='"+data.url+"'/>";
}
</script>

Upvotes: 0

Related Questions