loop through Object in Javascript get from PHP
310
Hello I have a PHP script that returns the following JSON :
[
{
"zone_name": "1st_zone"
},
{
"coordinates": [
"51.56256,-0.37903",
"51.50789,-0.19913",
"51.58475,-0.06729",
"51.61461,-0.19638",
"51.5711,-0.28152"
]
},
{
"zone_name": "2nd_zone"
},
{
"coordinates": [
"51.56256,-0.37903",
"51.50789,-0.19913",
"51.58475,-0.06729",
"51.61461,-0.19638",
"51.5711,-0.28152",
"51.57707,0.11398",
"51.48651,0.12497",
"51.56939,0.28427"
]
}
]
In Javascript I'm doing an AJAX call like that :
$.ajax({
type: "POST",
cache: false,
url: "load_zone.php",
dataType: 'json',
success:function(response){
for(var i =0; i<response.length; i++){
console.log(response[i]);
}
},
error:function(){
}
});
I get this result in console :
Object { zone_name="1st_zone"}
Object { coordinates=[5]}
Object { zone_name="2nd_zone"}
Object { coordinates=[8]}
How can I print each zone_name and coordinates separately?
Thanks
Answer
Solution:
This will give you the respective zone names and coordinates. Your current JSON has an array of objects which list the zone names and coordinates as successive elements of the array.
But you should try to change your json to look something like this:
Which will mean that the array would contain objects representing a zone with its coordinates. Which can then be accessed like
response[i].zone_name
andresponse[i].coordinates
.Answer
Solution:
do like this: