0

Helle there, I created a code that read a json url and return the object, but I need put this object in the variable. Here is my code:

<?php
    $cep = 35400000;
?>

<script type="text/javascript">
    function lerArquivo(arquivo, callback) {
        var rawFile = new XMLHttpRequest();
        rawFile.overrideMimeType("application/json");
        rawFile.open("GET", arquivo, true);
        rawFile.onreadystatechange = function() {
            if (rawFile.readyState === 4 && rawFile.status == "200") {
                callback(rawFile.responseText);
            }
        }
        return rawFile.send(null);
    }

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

var cidade = lerArquivo(url, function(texto){
    var dado = JSON.parse(texto);
});
    document.write(cidade); //It does not working!
</script>

I can not use a ajax. Someone can help? Because I need use this variable.

  • Tehnically you are using AJAX. And are you confusing JSON and XML? Have you tried `document.write(dado)` in your callback function? – Vid Sep 28 '21 at 20:20
  • With your current code, you're trying to print the return value of your lerArquivo function, which is undefined, because XMLHttpRequest.send() method always returns undefined. – Vid Sep 28 '21 at 20:21
  • I know if I put document.write(dado) inside to the callback the parameter of the function learquivo, I will see the object, but I want to use this object in a variable, because I need to put inside the database using php. – Rodrigo Franco Sep 28 '21 at 20:56

0 Answers0