gpt4 book ai didi

javascript - 如何使用js提取ajax调用的响应?

转载 作者:行者123 更新时间:2023-11-28 13:12:05 25 4
gpt4 key购买 nike

我的函数有一个 ajax 调用

js部分

_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);
});

php部分

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

这里的 name、mob-num 和 email 是键,我正在尝试提取它们的值

我已经尝试过

var res = eval("(" + response + ")");
var data = res.msg;
alert(data[name]);//which is the first key

这不起作用。我怎样才能提取这个?

最佳答案

假设您有以下响应:

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

要访问属性,例如第一条消息的电子邮件,您可以执行以下操作:

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);

关于javascript - 如何使用js提取ajax调用的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41610375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com