Error when picking up JSON elements

Asked

Viewed 207 times

1

Speak guys, blz? I have a problem when it comes to receiving the answer in JSON from Ajax, I can not popular all states in select. Although it is inside of a being it takes only the last element, ie it goes through all the states but only stores the last... If anyone knows how to proceed with the script, I’d appreciate it!

If it were in Jquery it would use . html() to assign the value, but in pure JS?

select populates only with Tocantins the last element

In my case the.json states file is local

LINK states-cities.json https://gist.github.com/lucashort7/313bec7d4a8b82472ac19993681d71c2

Thank you!

(function(){
    'use strict';

    var ajax = new XMLHttpRequest();

    var $estado = document.querySelector('[data-js="estado"]');

    ajax.open('GET', 'json/estados-cidades.json', true);
    ajax.send(null);

    var options = "<option value=''>selecione o seu estado</option>";
    $estado.innerHTML = options;

    ajax.addEventListener('readystatechange', function(){

        if(ajax.readyState === 4 && ajax.status === 200){
            var data = JSON.parse(ajax.responseText);

            for(var i = 0; i < data.estados.length; i++){
                options = `<option value='${data.estados[i]["sigla"]}'>${data.estados[i]["nome"]}</option>`;

                //$estado.appendChild(options); também nao funciona
                $estado.innerHTML = options;   
            }

        }

    }, false);



})();

2 answers

1

You are overwriting the content whenever it calls

$estado.innerHTML = options;

Place content in a variable and then apply to HTML

(function(){
    'use strict';

var ajax = new XMLHttpRequest();

var $estado = document.querySelector('[data-js="estado"]');

ajax.open('GET', 'json/estados-cidades.json', true);
ajax.send(null);

var options = "<option value=''>selecione o seu estado</option>";
$estado.innerHTML = options;

ajax.addEventListener('readystatechange', function(){

    if(ajax.readyState === 4 && ajax.status === 200){
        var data = JSON.parse(ajax.responseText);

        for(var i = 0; i < data.estados.length; i++){
            options = options + `<option value='${data.estados[i]["sigla"]}'>${data.estados[i]["nome"]}</option>`;                

        }
        $estado.innerHTML = options;   

    }

}, false);

})();

0

Actually inside the for I wasn’t getting the options variable itself I didn’t notice she was missing even options += ....

Thanks Luciano Marqueto, thanks anyway!

  • 1

    Hi Igor! If Luciano’s answer solved the problem you can click to mark as accepted,

Browser other questions tagged

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