2016-01-06 76 views
0

從我的數據庫中,我提取了一些數據作爲json string.But很遺憾,我無法訪問作爲響應返回的數據。以下是我的PHP網頁中抓取數據:作爲json使用ajax返回的Acces響應值

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'; 
      } 
     } 
    } 

它返回如下:

Enter image description here 並在接收部分下面:(它目前打印未定義

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


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

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

try .. alert(response [0] ['answer_body']); –

+0

仍未定義 –

+0

解決了它..使用var obj = $ parseJSON(response)解析json字符串。 \t \t \t \t alert(obj [0] ['answer_body']); –

回答

0

您的response是一個字符串,而不是一個數組。您應該使用getJSON()以確保將響應解析爲對象:

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