json_encode无法处理PDO获取的数据

我在这里干涸。 用户单击选择列表上的选项,然后jQuery发送xhr到服务器进行处理,这里没什么特别的,代码工作正常(firebug显示正确的发布数据)。

然后是一个简单的代码,用于从W_id == $val的数据库中返回行,然后获取结果为$result ,然后将结果作为json响应:

 public function getCities($val) { $sth = $this->db->prepare("SELECT id, name FROM cities WHERE w_id = :w_id"); $sth->execute(array(':w_id' => $val)); $result = $sth->fetchAll(PDO::FETCH_ASSOC); //print_r($result); header("content-type:application/json"); echo json_encode($result); } 

Firebug显示Post数据但没有响应。 但是当我取消注释print_r ,它会向我显示一个数组作为响应:

 Array( [0] => Array( [id] => 1401 [name] => Aïn Bouchekif ) [1] => Array( [id] => 1402 [name] => Aïn Deheb ) [2] => Array( [id] => 1403 [name] => Aïn El Hadid ) and so on... 

这意味着可以返回结果,但我不知道如何对它们进行jsonify。 任何帮助表示赞赏,谢谢。

我认为这是一个编码问题,您可以使用json_last_error()来validation这个想法。 您可以在标题中添加charset=utf-8

 $result = $sth->fetchAll(PDO::FETCH_ASSOC); //print_r($result); header("Content-type: application/json; charset=utf-8"); // <-- Here echo json_encode($result); echo json_last_error(); // <-- Here 

这对我有用 : UTF-8字符编码战json_encode()

 public function getCities($val) { $sth = $this->db->prepare("SELECT id, name FROM cities WHERE w_id = :w_id"); $sth->execute(array(':w_id' => $val)); header("Content-type: application/json; charset=utf-8"); $rows = array(); while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { $rows[] = array_map('utf8_encode', $row); } echo json_encode($rows); } 

我在这里找到了其他答案如何用法语口音json_encode数组? 但不断收到通知,发现非法人物。