简体   繁体   中英

Acces response value returned as json using ajax

From my database i fetched some data as json string.But unfortunately i can't access the data which is returned as response. Following is my php page to fetch data:

  require_once '../core/init.php';
   $answer=$_POST['answer_body'];
   $post_id=$_POST['userpost_post_id'];
   $answerer=$_POST['users_user_id'];
   if(isset($answer,$post_id,$answerer)){
     if(!empty($answer) && !empty($post_id) && !empty($answerer)){
           $db=DB::getInstance();
           if($result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result()){
                echo json_encode($result);
           }else{
              echo 'there was a problem';
           }
       }
   }

It returned as following:

在此处输入图片说明 and in the receiving part is following:( it currently prints undefined )

$.ajax('../includes/verifyanswer.php',{
        data:data,
        type:"POST",
        datatype:'json',
        success:function(response){


           alert(response['answer_body']); // prints undefined

        },
        error:function(response){
              alert(response);
           }
    })

Your response is a string, not an array. You should use getJSON() to make sure the response is parsed into an object :

$.getJSON(
    '../includes/verifyanswer.php',
    data,
    function(response) {
        alert(response.answer_body);
    }
);

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