Skip to content

Instantly share code, notes, and snippets.

@liuxiaomingskm
Last active February 1, 2020 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuxiaomingskm/f5c64d724914ce8bf46ce341fad822ea to your computer and use it in GitHub Desktop.
Save liuxiaomingskm/f5c64d724914ce8bf46ce341fad822ea to your computer and use it in GitHub Desktop.
Random Dog Pictures AJAX(练习了传统XMLHttpRequest的写法并了解XML的work flow)
<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>
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();
});
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