[英]How to get data from json array in JavaScript?
我有php函数,它将数组返回到JavaScript像这样:
$data['first'] = 10; $data['second'] = 20; echo json_enocde($data);
在JavaScript中,返回的值称为response。 在阅读有关json的信息后,我需要显示这些值并进行如下尝试:
alert("First: " + response.first + " Second: " + response.second);
但是此代码仅在response.first和response.second位置显示未定义的值。 如果我写警报(响应),那么我会得到答案:
{"first":"10","second":"20"}
这意味着JavaScript正在获取信息。 如何从JSON编码数组中分别获取值?
问候
使用JSON.parse()
将JSON字符串转换为JavaScript对象。
看起来您仍然具有JSON字符串,并且没有将其解析为JS对象。 使用JSON.parse
:
var jsonString = '{"first":"10","second":"20"}'; // from whereever
var obj = JSON.parse(jsonString);
alert("First: " + response.first + " Second: " + response.second);
alert(obj); // should now be "[object Object]"
像这样使用eval(不推荐)
var res = eval(response); //as you can see people are against it so I am editing the answer
使用JSON.parse()
或者,如果您使用jQuery
jQuery.parseJSON(response);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.