0
Hello!
I am using the code below to get address through the CEP informed.
It works, but when typing an invalid zip code or 0000000, I get the return {"erro":true}
. How can I turn this return into an Alert with the code below:
console.log("webservice cep");
$("#numero").attr("readOnly", true);
$("#complemento").attr("readOnly", true);
//var lastCepCheck = '';
var ultimo_cep = '';
document.getElementById('cep').addEventListener('keyup', function() {
//Impede inserir algo alem de Números
//this.value = this.value.replace(/[^0-9]/, "");
//Pega apenas os números
var cep = this.value.replace(/[^0-9]/, "");
//Só pesquisa se tiver 8 caracteres e o ultimo cep pesquisado seja diferente do atual.
if (cep.length != 8 || ultimo_cep == cep) {
return false;
}
ultimo_cep = cep;
ajax = new XMLHttpRequest();
var url = "http://viacep.com.br/ws/" + cep + "/json/";
ajax.open('GET', url, true);
ajax.send();
ajax.onreadystatechange = function() {
//console.log(ajax.status);
if (ajax.readyState == 4 && ajax.status == 200) {
var json = JSON.parse(ajax.responseText);
console.log(ajax.responseText);
if (json == "{erro: true}"){
alert("erro");
}
else {
$("#logradouro").val(json.logradouro);
$("#bairro").val(json.bairro);
$("#cidade").val(json.localidade);
$("#uf").val(json.uf);
$("#numero").attr("readOnly", false);
$("#complemento").attr("readOnly", false);
$("#numero").focus();
}
}
}
});
I get this:
Uncaught TypeError: json.stringify is not a function
 at XMLHttpRequest.ajax.onreadystatechange
– Wagner Fillio
If you uncomment the line
//console.log(ajax.status);
, what code shows? If it is different from 200, it will not even go through the error check.– Carlos Andrade
displays code 200
– Wagner Fillio
Can you find the name of the property that returns the error? In this case, just replace.
if (json.propriedade.stringify({erro: true}) == '{"erro":true}')
 alert("erro");
– Carlos Andrade
Also try to:
if (JSON.stringify(json) == '{"erro":true}') alert("erro");
– Carlos Andrade
Perfect, look how it turned out!
if (JSON.stringify(json) == '{"erro":true}') {alert("erro");}
– Wagner Fillio
Update the reply to mark it! Thanks!!
– Wagner Fillio
https://answall.com/posts/215227/revisions
– Carlos Andrade