A Pen by Devyendu Shekhar Choudhary on CodePen.
Created
February 15, 2018 05:33
-
-
Save dsc712/3f9324bb893458283780b437064e493c to your computer and use it in GitHub Desktop.
ajax using xhr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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