简体   繁体   中英

Getting specific value in array returned by JSON, using javascript

I'm having trouble getting the content in an Array returning from a PHP file, using an AJAX call.

Below it's a part of my php file in which i get the content from a database:

<?
...
$sql = "SELECT id,
               nome
        FROM  (SELECT  cod_district AS ID, 
                       district AS nome
               FROM    pms_district
               WHERE   cod_pais =".$cod_pais.")
        ORDER BY id";
$state = array();
if ($db->query($sql)) {
    while ($db->next_record()) {
        $state['id']    = $db->f('id');
        $state['nome'] = utf8_encode($db->f('nome'));
        $return_state[] = $state;
    }
}

$sql = "SELECT id,
               nome
        FROM  (SELECT  cod_cidade AS ID,
                       cidade AS nome
               FROM    c_cidade
               WHERE   cod_pais =".$cod_pais.")
        ORDER BY id";

$city = array();
if ($db->query($sql)) {
    while ($db->next_record()) {
        $city['id'] = $db->f('id');
        $city['nome'] = utf8_encode($db->f('nome'));
        $return_city[] = $city;
    }
}

$return = array('estado' => $return_state, 
                'cidade' => $return_city
                );

echo json_encode($return);
?>

I think the problem might be in the way that the array is created, but i can't get it to work.

I am getting this result from the request:

{ "cidade" : [ { "id" : "5825",
    "nome" : "Almeria"
  },
  (...)
  { "id" : "6189",
    "nome" : "ESPANHA"
  }
],
"estado" : [ { "id" : "276",
    "nome" : "Madrid"
  },
  { "id" : "277",
    "nome" : "Andaluzia"
  },
  (...)
  { "id" : "294",
    "nome" : "Região de Múrcia"
  }
]
}

I'm not beeing able to access the data that is beeing responsed by the AJAX request, when trying to get a specific object.

(I am getting the response shown above when doing a console.log(xmlhttp.responseText))

This is the code used to acces the values returned:

var obj = xmlhttp.responseText;
var parsed = JSON.parse(obj);
parsed[0].nome;

This is where the error comes from:

TypeError: parsed[0] is undefined

I am doing this to go through every element inside "cidade".

PS: I can only use javascript.

Thanks,

Your response is not array so you cannot reference it with numeric indexes. Use parsed["cidade"][0].nome instead.

Your response is JSON. You can access your data like below.

var cidade = parsed.cidade;
OR
var cidade = parsed['cidade'];

for(var i in cidade)
{
     var id = cidade[i].id;
     var nome = cidade[i].nome;
}

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