problem reading array

0

I am receiving this array of objects as a callback with a ajax request

[
{"nombre":"Kabul"},
{"nombre":"Qandahar"},
{"nombre":"Herat"},
{"nombre":"Mazar-e-Sharif"},
{"nombre":"Otra"}
]

This is the way I read the array of objects and then press the results in a div

        $.ajax({

        url:url,
        type:"POST",
        datatype:"JSON",
        contenttype:"application/json",

        }).done(function(response){

         var text=response;
         var obj=JSON.parse(text);
         var array=[];

        obj.forEach( ciudad => array.push(ciudad.nombre) );
        //al imprimir esto en la consola el resultado es exitoso ejemplo
        //["kabul","Qandhar","Herat","Mazart-e-Sharif","otra"]
        console.log(array)
        //trato de imprimir el array en un select de esta manera 
        for(i=0; i< array.length; i++){

           $("#myCities").html(array[i])

        }

        })

although the push is successfully done in the array at the time of printing the array in the div it only prints the last index of the array ie another I do not understand why if the array is fine and I'm assuming that the way I'm reading it with the for is correct, some help?

    
asked by andy gibbs 01.11.2018 в 19:39
source

2 answers

1

To achieve what you want you need to clean the div every time you make the Ajax call. Then to add the options you use append . It would stay like this:

$.ajax({

    url:url,
    type:"POST",
    datatype:"JSON",
    contenttype:"application/json",

    }).done(function(response){

     var text=response;
     var obj=JSON.parse(text);
     var array=[];

    obj.forEach( ciudad => array.push(ciudad.nombre) );
    //al imprimir esto en la consola el resultado es exitoso ejemplo
    //["kabul","Qandhar","Herat","Mazart-e-Sharif","otra"]
    console.log(array)
    //trato de imprimir el array en un select de esta manera 
    $("#myCities").html("");
    for(i=0; i< array.length; i++){

       $("#myCities").append(array[i]);

    }

    })
    
answered by 01.11.2018 в 19:47
1

Inteta with this:

        var datos="";
        $.ajax({

        url:url,
        type:"POST",
        datatype:"JSON",
        contenttype:"application/json",

        }).done(function(response){

         var text=response;
         var obj=JSON.parse(text);
         var array=[];

        obj.forEach( ciudad => array.push(ciudad.nombre) );
        //al imprimir esto en la consola el resultado es exitoso ejemplo
        //["kabul","Qandhar","Herat","Mazart-e-Sharif","otra"]
        console.log(array)
        //trato de imprimir el array en un select de esta manera 
        for(i=0; i< array.length; i++){

           datos+=array[i];

        }

        });
$("#myCities").html(datos)

by assigning $("#myCities").html(array[i]) you are replacing the text passed by the next one in each interacion!

    
answered by 01.11.2018 в 19:49