Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?可能的重复:我有一个嵌套的数据结构/ JSON,我如何访问一个特定的值?
i have a javascript which does a XMLHttp request to a php file, which in turn queries a mysql table and returns a JSON array... but somehow i cannot access individual elements of the array. here is the javascript:
我有一个javascript,它对php文件执行XMLHttp请求,而php文件反过来查询mysql表并返回JSON数组……但是我无法访问数组的各个元素。这是javascript:
<script type="text/javascript">
function show(){
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange= function () {
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var response= new Array();
response=xmlhttp.response;
alert(response);
}
}
xmlhttp.open('GET','test.php', true);
xmlhttp.send();
}
</script>
and this is the php script:
这是php脚本:
mysql_select_db('testpolaroid') or die ('Unable to select database!');
$query = 'SELECT * FROM images';
$result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
if(mysql_num_rows($result) > 0)
{
$row = mysql_fetch_assoc($result);
echo json_encode($json);
}
the response that i get is :
我得到的回答是:
{"imageid":"11","location":"11.jpg"}
1 个解决方案
#1
3
You need to parse the JSON first with JSON.parse
, code would look like:
您需要先用JSON解析JSON。解析代码如下:
var response = JSON.parse(xmlhttp.responseText);
var imageid = response["imageid"];
#1
3
You need to parse the JSON first with JSON.parse
, code would look like:
您需要先用JSON解析JSON。解析代码如下:
var response = JSON.parse(xmlhttp.responseText);
var imageid = response["imageid"];