2017-02-12 121 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