A Pen by liuxiaomingskm on CodePen.
Last active
February 1, 2020 01:04
-
-
Save liuxiaomingskm/f5c64d724914ce8bf46ce341fad822ea to your computer and use it in GitHub Desktop.
Random Dog Pictures AJAX(练习了传统XMLHttpRequest的写法并了解XML的work flow)
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 Random Dog Pictures</h1> | |
<img id="photo" src="https:\/\/dog.ceo\/api\/img\/deerhound-scottish\/n02092002_6780.jpg" alt=""> | |
<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 img = document.querySelector("#photo"); | |
//listen for click | |
btn.addEventListener("click", function(){ | |
//make the request | |
var XHR = new XMLHttpRequest(); | |
XHR.onreadystatechange = function(){ | |
if (XHR.readyState == 4 && XHR.status == 200){ | |
var url = JSON.parse(XHR.responseText).message; | |
img.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
img { | |
height: 200px; | |
} | |
.container { | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
} | |
button { | |
margin: 20px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment