Manipulate json with ajax and use your data separately

Asked

Viewed 180 times

1

PHP:

if (@mysql_num_rows($resultados) > 0){
      while ($linha = mysql_fetch_array($sql)) 
          $retorno = array($linha);           
         // print_r(json_encode($retorno));
          echo json_encode($retorno);
}   

How to manipulate, that is, break this json with ajax so that you can use your data separately?

The function is like this: That’s how I tried, but it didn’t work... Look how I did:

function marcacao(){       
   $.ajax({
            type: "get",
            url: $server+"/conecta.php",
            data: "acao=marcacao",
            success: function(data) {
                var resultado = JSON.parse(data);
                console.log(resultado);  
            for(var i = 0; i<=data.length; i++){
                $Jlati = resultado.employees[1];
                $Jlng = resultado.employees[2];

                var map = new google.maps.Map(
                        document.getElementById("map"), 
                        { 
                          center : new google.maps.LatLng($Jlati[i], $Jlng[i]), 
                          zoom : 5, 
                          mapTypeId : google.maps.MapTypeId.ROADMAP 
                        }
                );


                var image = 'www/images/ray001.png';

                var marker = new google.maps.Marker(
                    {
                            title : "VOCÊ ESTÁ AQUI: "+$Jlati[i]+", "+$Jlng[i],
                            position : new google.maps.LatLng($Jlati[i], $Jlng[i]),
                            map: map,
                            icon: image
                     });

                marker.setMap(map);  

              }
            }

        });

    }
    marcacao();

But nothing happens at all...

1 answer

2

Without having the right data from your Json it is difficult to build a code for your specific case, so I’ll put an example of how you can use a Json and then you adapt it to your case, ok?

In it we have a Json within a variable, we parse it into an object, we take an HTML object and we put the value of the object generated from the Json into the HTML.

var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
<p id="demo">O valor do Json entra aqui.</p>

In the above model the value shown is Anna Smith and is set here: obj.employees[1]

Have the code executed and you will see the result. This code came from this link, in it you can change the code and see the result.

Browser other questions tagged

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