我的功能上有一个ajax调用
_this.ajaxPost(appUrl + "reports/appointment/save", post_str, function(response) {
var res = eval("(" + response + ")");
if (!res.error) {
var data = res.msg;
} else {
if (res.status == "error") {
_this.showPopMsg("error", 'Error when updating db ', res.msg);
}
}
}, function(response) {
alert(response);
var res = eval("(" + response + ")");
_this.showPopMsg("error", 'Updating DB', res.msg);
});
echo json_encode(array("error"=> false, "status"=>"success", "msg"=>$conditions['reg']->result()));
返回响应,如
{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}
我正在尝试使用 js 提取 msg 部分,msg部分包含一个类似
的数组[{"name":"dream hunter","mob_num":"9876543210","email":"afl@thnfgd"}]
这里名称,mob-num和电子邮件是密钥,我正在尝试提取其值
我试过了
var res = eval("(" + response + ")");
var data = res.msg;
alert(data[name]);//which is the first key
哪个不行。我怎样才能提取这个?
答案 0 :(得分:3)
假设您有以下回复:
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}'
使用JSON.Parse,您可以提取对象:
var y = JSON.parse(x);
现在你有一个像这样的对象:
{
error:false,
msg: [{
email: "afl@thnfgd"
mob_num: "9876543210"
name: "dreamhunter"
}],
status:"success"
}
要访问第一条消息的属性,例如email
,您可以执行此操作:
console.log(y.msg[0].email);
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}'
var y = JSON.parse(x);
console.log('msg[0].email: ', y.msg[0].email);
答案 1 :(得分:1)
您可以使用以下方式查看数据: -
alert(data[0].name);
答案 2 :(得分:1)
使用JSON对象方法在javascript中处理JSON。
例如
var data = JSON.parse('{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}')
alert(data.msg[0].name)