【问题标题】:JSON.parse: unexpected end of dataJSON.parse:数据意外结束
【发布时间】:2017-10-04 21:29:52
【问题描述】:

我是 Angularjs 和 SlimPHP 的新手,我在将数据解析为 json 时遇到了一些麻烦。我刚刚启动了一个新应用程序,但我不知道为什么它不起作用。

这是我的控制器的功能,它似乎正在工作(我可以使用 print_r 来显示 $poles),但不能返回 Json。在 Firefox 网络中,我有错误:“SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data”。

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

formDAO.php 中的 getPoles() 函数:

    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
    ))

【问题讨论】:

    标签: php json slim


    【解决方案1】:

    像这样返回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);
    }
    

    【讨论】:

    • 谢谢,但不幸的是,这并不能解决问题。我仍然有同样的错误
    • 您是否在$poles 中获得了波兰人的结果?可以发一下吗?
    【解决方案2】:

    我想我找到了问题的根源。在数组中,我没有复制完整的“libelle”字段,因为它们很长。 我刚刚意识到这是问题所在,因为数据是法语的,所以它们有很多不支持的口音。

    我只需要更新我的数据库连接的这一行:

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

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 2017-05-08
      • 1970-01-01
      • 2012-11-25
      • 2020-11-18
      • 2018-05-01
      • 2021-05-01
      相关资源
      最近更新 更多