Json script with problem, Google Chrome locks and does not work in another browser

Asked

Viewed 434 times

0

I am trying to auto-fill data from the ZIP code, with the following code.

$("#cep").blur(function() {
  var cep = this.value.replace(/[^0-9]/, "");
  if (cep.length != 8) {
    return false;
  }

  var url = "http://viacep.com.br/ws/" + cep + "/json/";

  $.getJSON(url, function(dadosRetorno) {
    try {
      $("#endereco").val(dadosRetorno.logradouro);
      $("#bairro").val(dadosRetorno.bairro);
      $("#cidade").val(dadosRetorno.localidade);
      $("#uf").val(dadosRetorno.uf);
    } catch (ex) {}
  });
});
<div class="form-group col-md-3 col-sm-12">
  <label id="nome">CEP</label>
  <input type="text" name="cep" id="cep" class="form-control" required>
</div>
<div class="form-group col-md-3 col-sm-12">
  <label id="nome">Endereço</label>
  <input type="text" name="endereco" id="endereco" class="form-control" readonly>
</div>
<div class="form-group col-md-3 col-sm-12">
  <label id="nome">Número</label>
  <input type="number" name="numero" id="numero" class="form-control" required>
</div>
<div class="form-group col-md-3 col-sm-12">
  <label id="nome">Bairro</label>
  <input type="text" name="bairro" id="bairro" class="form-control" readonly>
</div>

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

But it does not work in Firefox and Chrome it from the error that the unsafe script has been blocked, but if I choose the option "Load Insecure Script" the script works normally, tried on multiple computers and on 2 phones, and the same problem.

imagem do erro que o Google Chrome aponta

Has anyone ever had this problem or anything like that, and can shed some light on that doubt???

  • Have you tried using the example in the documentation. Using HTTPS instead of HTTP? $. getJSON("https://viacep.com.br/ws/"+ cep +"/json/? callback=?" , Function(data from){}

  • Dude, I tested here https://jsfiddle.net/jediWhatever/c4ku0r7p/3/ I only changed $.getJson for $.get and https

1 answer

0


Starting with version 56, Chrome went on to warn about scripts loaded from insecure sources, ie via HTTP.

To solve your problem, the query should be done using a secure resource (HTTPS). In your code, Voce should change this line:

var url = "http://viacep.com.br/ws/" + cep + "/json/";

for

var url = "https://viacep.com.br/ws/" + cep + "/json/";

The site you are consuming the API seems to provide this option. See this example using fetch.

EDIT

As a general rule, the jQuery script you are loading should also make explicit the HTTPS protocol:

Change

//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

for

https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
  • Guy worked out, thank you very much, it now works even in Firefox

Browser other questions tagged

You are not signed in. Login or sign up in order to post.