Created
March 14, 2018 18:18
-
-
Save crisgon/25017dbcfe13473a20f2bf6bb6b495bf to your computer and use it in GitHub Desktop.
Usando uma API de Ceps
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
(function(win, doc){ | |
'use strict'; | |
let formAdress = { | |
cep: doc.querySelector('[data-js="cep"]'), | |
state: doc.querySelector('[data-js="state"]'), | |
city: doc.querySelector('[data-js="city"]'), | |
street: doc.querySelector('[data-js="street"]'), | |
district: doc.querySelector('[data-js="district"]') | |
} | |
let $button = doc.querySelector('[data-js="button"]'); | |
let adressInfo; | |
let cep; | |
$button.addEventListener('click', function(event){ | |
event.preventDefault(); | |
getAdress(formAdress.cep.value); | |
setTimeout(() => { | |
console.log(showAdress()); | |
}, 1000); | |
}); | |
function getAdress (url) { | |
let conection = new XMLHttpRequest(); | |
conection.open('get', 'http://apps.widenet.com.br/busca-cep/api/cep/'+ url.match(/\d/g) +'.json'); | |
conection.addEventListener('readystatechange', ()=> { | |
if(isRequestOk(conection)) | |
adressInfo = JSON.parse(conection.responseText); | |
}); | |
conection.send(); | |
} | |
function isRequestOk (conection) { | |
return conection.readyState === 4 && conection.status === 200; | |
} | |
function showAdress() { | |
if(adressInfo.status === 0) | |
return adressInfo.message; | |
formAdress.state.value = adressInfo.state; | |
formAdress.city.value = adressInfo.city; | |
formAdress.street.value = adressInfo.address; | |
formAdress.district.value = adressInfo.district; | |
} | |
}(window, document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment