简体   繁体   中英

How to extract the response from ajax call using js?

I have a ajax call on my function

js part

_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 part

echo json_encode(array("error"=> false, "status"=>"success", "msg"=>$conditions['reg']->result()));

which returns a response like,

{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}

and I'm trying to extract the msg part using js , the msg part contains an array like

[{"name":"dream hunter","mob_num":"9876543210","email":"afl@thnfgd"}]

and here name,mob-num and email are keys and I'm trying to extract their values

I have tried

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

which is not working. How can I extract this?

Assuming you have the following response:

var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}'

Using JSON.Parse you can extract the object:

var y = JSON.parse(x);

Now you have an object like this:

{
    error:false,
    msg: [{
        email: "afl@thnfgd"
        mob_num: "9876543210"
        name: "dreamhunter"
    }],
    status:"success"
}

To access the properties, such as the email for example, of the first message you can do this:

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

您可以使用以下数据查看数据:

alert(data[0].name);

Use the JSON object methods to handle JSON in javascript.

For instance

var data = JSON.parse('{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl@thnfgd"}]}')

alert(data.msg[0].name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM