Use Ajax Json return in HTML

Asked

Viewed 267 times

-1

Hi... I have the following codes

HTML

<div class="escolha">
          <h5>ESCOLHA A CIDADE</h5>
          <select id="selectMunic" onchange="getMunic(this);">
          </select>
          <div class="Indice"><span>Indice:</span><strong>moradas</strong></div    

 </div>

Jquery and AJAX

Getting the cities to display in select, each city has its own Address Index, returned in JSON

<script>
    var getMunics = function(){
        $.ajax({
          url: "/city.json", //apenas exemplo... passo a url completa aqui
          method: "GET"
        }).done(function( munics ) {
            $(munics).each(function(){
                $("#selectMunic").append("<option value='" + this.munic + "' >" + this.munic + "</option>");
            })
        });
    }

Returning a specific city after selecting

var getMunic = function(select){
        $.ajax({
          url: "/city.json" + "?munic=" + select.value,
          method: "GET"
        }).done(function( munics ) {
            if(munics.length > 0){
                var munic = munics[0];
                console.log(munic);
            }
        });

    }

I checked on the console and is returning to the city and the address Index How do I display the Intel in HTML?

addresses - Naturally I know that so can’t rs

On the console I confirmed and returned as in the example below

{
   id: 1, 
   munic: "Caxias do Sul",
   moradas: 1000 
}

I’m sorry if I’m a little confused, and my first question on Stackoverflow and also the lack of accents in the sentences.

Thank you

1 answer

0

I think I’ve got a way...

JAVASCRIPT

var getMunic = function(select){
        $.ajax({
          url: "/city.json" + "?munic=" + select.value,
          method: "GET"
        }).done(function( munics ) {
            if(munics.length > 0){
                var munic = munics[0];

                //determinei aqui um ID para ser usado no HTML, e eu tenho o 
                //objeto munic com os valores... ao escolher a chave morada, 
                //ele obetem o valor correspondente.

                document.getElementById("morada").innerHTML = munic.morada;

            }
        });

    }

I determined here an ID to be used in HTML, and I have the object munic with the values... when choosing the address key, it obeys the corresponding value, for example, 1000

HTML

<div class="Indice"><span>Indice:</span><strong><b id="morada"></b></strong></div> 

There I am accessing by ID the information...

Very cool. just as are more data I will have to do one by one what can be a little laborious but will work.

Thank you and I hope I can help someone.

Browser other questions tagged

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