2017-02-12 130 views
0

嘿我不經常使用PHP很可能一年一次,我有很多麻煩返回數據正確。基本上我得到一個對象,似乎包含我的數據在響應文本,我不知道爲什麼。如果有人能向我解釋爲什麼會發生這種情況,我會非常感激!不正確地返回JSON數據

enter image description here

這是從後端

if(isset($_POST['action']) && !empty($_POST['action'])) { 
    switch ($_POST['action']){ 
     case'getCandidates' : 
     { 
      $bus = array(
       'latitude' => $row['lat'], 
       'longitude' => $row['lng'], 
       'icon' => './images/' . $row['busColor'] . '.png' 
      ); 
      array_push($json, $bus); 
      $query = "SELECT * from candidates WHERE status = '$status' AND category = '$category' AND location = '$location'"; 
      $returnRows = $db->con->query($query); 
      if ($returnRows->num_rows > 0) { 
       $x = 0; 
       // output data of each row 
       while($row = $returnRows->fetch_assoc()) { 
        $object = new stdClass(); 
        $object->status = $row["status"]; 
        $object->first_name = $row["first_name"]; 
        $object->last_name = $row["last_name"]; 
        $object->category = $row["category"]; 

        array_push($aResult, $object); 

       } 
      } else { 
       $aResult[0] = "No results"; 
      } 

//    $aResult['result'] = mysql_fetch_object($returnRows);; 
      } 

代碼,這是前端代碼

returnedCandidates = $.ajax({ 
    url: "../php/admin.php", 
    type: 'POST', 
    dataType: 'json', 
    data: {action: 'getCandidates'}, 
    success: function(data, textStatus, jqXHR) { 

     alert(data); 
    }}); 
console.log(JSON.parse(returnedCandidates[0])); 

並且這是用PHP返回數據的行。我忘了添加它。

print_r(json_encode($ aResult));

+0

抱歉,我使用的print_r返回 – Seamy

+0

不要!而是使用'echo json_encode($ aResult);'[The manual](http://php.net/manual/en/function.json-encode.php) – RiggsFolly

+0

什麼是temp1?它是'數據'嗎?如果不是數據中返回的內容? – LYu

回答

0

註釋行:

//print_r(json_encode ($aResult)); 


,並返回這樣的:

return (json_encode ($aResult)); 
0

不要使用print_r的退貨。

試試這個代碼:

header('Content-Type: application/json'); 
echo json_encode($aResult); 
+0

不是沒有運氣,這真的讓我煩惱。我通常在C#中工作,所以Php現在有點令人困惑 – Seamy

+0

這段代碼無法工作;)我的意思是,如果沒有您向我們展示的代碼的上下文知識,沒有人會給你更好的答案。 –

+0

我不知道。我實際上已經這樣做了,但是print r不是回聲,它所做的只是在responsetext中返回數據.....這就是我現在需要的。老實說,這對我來說有點頭疼。 – Seamy