Skip to content

Instantly share code, notes, and snippets.

@crisgon
Created March 14, 2018 18:18
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 crisgon/25017dbcfe13473a20f2bf6bb6b495bf to your computer and use it in GitHub Desktop.
Save crisgon/25017dbcfe13473a20f2bf6bb6b495bf to your computer and use it in GitHub Desktop.
Usando uma API de Ceps
(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