I'm having trouble getting the content in an Array returning from a PHP file, using an AJAX call.
我在使用AJAX调用从PHP文件返回的数组中获取内容时遇到问题。
Below it's a part of my php file in which i get the content from a database:
下面是我的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);
?>
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.
在尝试获取特定对象时,我无法访问AJAX请求响应的数据。
(I am getting the response shown above when doing a console.log(xmlhttp.responseText))
(在执行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
TypeError:解析[0]未定义
I am doing this to go through every element inside "cidade".
我这样做是为了浏览“cidade”中的每个元素。
PS: I can only use javascript.
PS:我只能使用javascript。
Thanks,
2 个解决方案
#1
0
Your response is JSON. You can access your data like below.
您的回复是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;
}
#2
0
Your response is not array so you cannot reference it with numeric indexes. Use parsed["cidade"][0].nome instead.
您的响应不是数组,因此您无法使用数字索引引用它。使用已解析的[“cidade”] [0] .nome。
#1
0
Your response is JSON. You can access your data like below.
您的回复是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;
}
#2
0
Your response is not array so you cannot reference it with numeric indexes. Use parsed["cidade"][0].nome instead.
您的响应不是数组,因此您无法使用数字索引引用它。使用已解析的[“cidade”] [0] .nome。