Skip to content

Instantly share code, notes, and snippets.

@dsc712
Created February 15, 2018 05:33
Show Gist options
  • Save dsc712/3f9324bb893458283780b437064e493c to your computer and use it in GitHub Desktop.
Save dsc712/3f9324bb893458283780b437064e493c to your computer and use it in GitHub Desktop.
ajax using xhr
<div class="container">
<h1>Welcome to dog pictures</h1>
<image id="photo" src="https://\/\/dog.ceo\/api\/img\/deerhound-scottish\/n02092002_6780.jpg" alt="dog"></image>
<button id="btn">get Random Dog!</button>
</div>
var btn = document.querySelector("#btn");
var photo = document.querySelector("#photo");
btn.addEventListener("click", function(){
var xhr =new XMLHttpRequest() ;
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200 )
{
var url = JSON.parse(xhr.responseText).message;
photo.src = url ;
}
}
xhr.open("GET","https://dog.ceo/api/breeds/image/random");
xhr.send();
});
.container{
display: flex ;
flex-direction : column ;
align-items : center ;
justify-content : center ;
}
#photo{
height : 200px ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment