使用javascript在JSON返回的数组中获取特定的值


Getting specific value in array returned by JSON, using javascript

使用AJAX调用从PHP文件返回的数组中获取内容遇到了麻烦。

下面是我的php文件的一部分,我从数据库中获取内容:

<?
...
$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);
?>

我认为问题可能是在数组创建的方式,但我不能让它工作。

我从请求中得到这个结果:

{ "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"
  }
]
}

当我试图获得一个特定的对象时,我无法访问AJAX请求所响应的数据。

(当执行console.log(xmlhttp.responseText)时,我得到如上所示的响应)

这是用来访问返回值的代码:

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

这就是错误的来源:

TypeError: parsed[0] is undefined

我这样做是为了遍历"cidade"中的每个元素。

PS:我只能用javascript。

谢谢,

您的响应是JSON。您可以像下面这样访问您的数据。

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

您的响应不是数组,因此您不能使用数字索引引用它。使用解析("上帝")[0]。省。