简体   繁体   中英

Retrieve value from JSON and generate HTML to each register

I'm having a little bit of trouble on how to create a JQuery structure to append a HTML code to each of the items returned by my JSON. Basically my doubt is on how to retrieve each of the JSON values and put it on a repetition structure to create the code that, by the end, should be printed on the app screen. It's all quite simple code as I'm just learning how to work with phonegap, webservices and stuff. Thanks in advance.

Just to enlighten any doubt: I want to create a panel to each element that the request returns on the JSON. The panel should contain a soccer championship and it's country as in the hardcoded example below: App Layout

webservice.js

function listaCampeonatos(){
$.ajax({
    url: 'http://localhost/projetos/centraljogos/webservice//listagem.php',
    type: 'GET',
    dataType: 'json',
    data: {type:'listaCampeonatos'},
    ContentType: 'application/json',
    success: function(response){
        //alert('Listagem bem sucedida!');
        //$('#resultado').html(JSON.stringify(response));

        console.log(response);

        for (i=0 ; i<response.length ; i++){
            alert('Entrou no for');
            $('#resultado').html(response[i].nome_campeonato);
        }
    },
    error: function(err){
        alert('Ocorreu um erro ao se comunicar com o servidor! Por favor, entre em contato com o administrador ou tente novamente mais tarde.');
        console.log(err);
    }
});

}

listagem.php

include './conexao.php';

header("Access-Control-Allow-Origin: *");

$link = conectar();

if ($_GET['type'] == "listaCampeonatos") {
    //echo 'Tipo de operação: ' . $_GET['type'] . '<br>';

    $query = "SELECT c.id AS id_campeonato, c.nome_camp AS nome_campeonato, p.nome_pais AS nome_pais
                  FROM tb_campeonato c
                  LEFT JOIN  tb_pais p ON p.id = c.tb_pais_id
                  LEFT JOIN  tb_partida pt ON pt.tb_campeonato_id = c.id
                  WHERE pt.flag_ativo = 1

                  GROUP BY p.nome_pais";

    $result = mysqli_query($link, $query);

    $registros = array();

    while ($reg = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $registros[] = array('Campeonatos' => $reg);
    }

    $saida = json_encode(array('Lista' => $registros));

    echo $saida;
}

jogos.html

<!-- COTAÇÕES INÍCIO -->
    <div id="painel_partidas" class="panel panel-primary panel-heading-margin">
        <div class="panel-heading">
            <center>
                <b>Brasil &raquo; Série A - 19/10/2016</b>
                <button data-toggle="collapse" data-target="#partida" class="btn btn-default btn-xs pull-right"><i class="fa fa-compress"></i></button>
            </center>
        </div>

        <div id="partida">
            <div class="w3-border">

                <center>
                    <button class="btn btn-xs btn-danger" onclick="listaCampeonatos()"><i class="fa fa-search"></i>
                    Testar JSON
                    </button>
                </center>

                <div id="resultado"></div>

                <!--COTAÇÕES AQUI-->

            </div>
        </div>
    </div>
    <!-- COTAÇÕES FIM -->

Make some modifications in listagem.php as given below

 while ($reg = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $registros[] = $reg;
    }

    $saida = json_encode($registros);

    echo $saida;

Now you will be able to loop through the returned response object in webservice.js

 success: function(response){
        //alert('Listagem bem sucedida!');
        //$('#resultado').html(JSON.stringify(response));

        console.log(response);

        for (i=0 ; i<response.length ; i++){
            alert('Entrou no for');
            $('#resultado').html(response[i].nome_campeonato);
        }
    }

Do not use $('#resultado').html(response[i].nome_campeonato) if you need all the values of response[i].nome_campeonato inside <div id="resultado"></div> .Instead use

$('#resultado').append(response[i].nome_campeonato +"<br>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM