Created
October 31, 2017 05:02
-
-
Save vickonrails/34647195b112e6c0731f2bf7c0f7f2b6 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Async request</title> | |
</head> | |
<body> | |
<p> click on the button to add an image to the page</p> | |
<button type="button">Get image</button> | |
<img src="" width="100%"> | |
</body> | |
<script> | |
//ES5 for simplicity. | |
function sendRequest(){ | |
var url; | |
url = "https://api.unsplash.com/search/photos/?query=home"; | |
var request = new XMLHttpRequest(); | |
request.onreadystatechange = handleRequest;// callback to insert the image into the page... | |
request.open('GET',url,true); | |
request.setRequestHeader('Authorization','Client-ID your-unique-id'); | |
request.send(); | |
function handleRequest(){ | |
if(this.readyState === 4 && this.status === 200){ | |
var response = JSON.parse(request.responseText); | |
var img = document.querySelector('img'); | |
img.src = response.results[0].urls.full; | |
} | |
} | |
} | |
var btn = document.querySelector('button'); | |
btn.addEventListener('click',sendRequest);//callback to handle the click event... | |
</script> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment