2017-10-04 84 views
2

我是Angularjs和SlimPHP的新手,我有一些麻煩將我的數據解析爲json。我剛開始一個新的應用程序,我不知道爲什麼這不起作用。JSON.parse:意外的數據結束

這裏是我的控制器似乎在工作的功能(我可以使用print_r來顯示$極點),但不能返回Json。在Firefox的網絡中,我有一個錯誤:「SyntaxError:JSON.parse:JSON數據第1行第1列的數據意外結束」。

public function getPoles($request, $response) { 

    $poles = $this->container['form.dao']->getPoles(); 
    if ($poles == null) { 
     return json_encode(["error" => "no data found"]); 
    } 

    return $response->withJson($poles, 200); 
} 

的getPoles從formDAO.php()函數:

public function getPoles() { 
    $request = "SELECT * FROM menu_pole ORDER BY id"; 
    try { 
     $stmt = $this->db->query($request); 
     $poles = $stmt->fetchAll(\PDO::FETCH_OBJ); 
     return $poles; 
    } catch(\PDOException $e) { 
     return '{"error":{"text":'. $e->getMessage() .'}}'; 
    } 
} 

我想我可能失去了一些東西明顯。

編輯:

隨着print_r的,我得到這個:

Array(
[0] => stdClass Object 
    (
     [id] => 1 
     [libelle] => GE 
    ) 

[1] => stdClass Object 
    (
     [id] => 2 
     [libelle] => GP 
    ) 

[2] => stdClass Object 
    (
     [id] => 3 
     [libelle] => GS 
    ) 

[3] => stdClass Object 
    (
     [id] => 4 
     [libelle] => NO 
    ) 

[4] => stdClass Object 
    (
     [id] => 5 
     [libelle] => DH 
    ) 

[5] => stdClass Object 
    (
     [id] => 6 
     [libelle] => CRC 
    ) 

[6] => stdClass Object 
    (
     [id] => 7 
     [libelle] => SG 
    )) 

回答

0

返回JSON這樣的:

public function getPoles($request, $response) { 

    $poles = $this->container['form.dao']->getPoles(); 
    if ($poles == null) { 
     $data['error'] = 'no data found'; 
     return json_encode($data); 
    } 

    return $response->withJson($poles, 200); 
} 
+0

謝謝,但不幸的是這並沒有解決問題。我仍然有同樣的錯誤 – Nagah

+1

你是否在'$ poles'中得到了極點的結果?你可以發佈嗎? –

0

我想我找到了問題的根源。在陣列中,我沒有複製完整的「libelle」字段,因爲它們很長。 我剛剛意識到這是問題,因爲數據是法文的,他們有很多不支持的口音。

我只是需要更新此行我的數據庫連接:

$db = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));