json_en code不工作的PDO获取的数据 [英] json_encode not working on PDO fetched data
问题描述
我挂干在这里。用户点击一个选择列表中的一个选项,然后jQuery的发送一个XHR的服务器来处理,这里没有什么特别,code完美的作品(萤火显示了正确的发布资料)。
I'm hanging dry here. The user clicks on an option on a select list, then jQuery sends an xhr to the server to process, nothing special here, code works perfectly (firebug shows correct Posted data).
然后一个简单的code,从一个数据库,其中 W_id == $ VAL
,然后取结果 $结果返回行
,然后回显结果作为JSON响应:
Then a simple code to return rows from a database where W_id == $val
, and then fetch results in $result
, then echo results as a json response:
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);
}
萤火虫显示后的数据,但没有任何反应。但是,当我取消对的print_r
,它显示了我一个数组作为响应:
Firebug shows the Post data but no Response. But when I uncomment the print_r
, it shows me an array as a Response:
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他们。任何帮助是AP preciated,谢谢。
Which means that there are results that can be returned, but I don't know how to jsonify them. Any help is appreciated, thanks.
推荐答案
我认为这是一个编码的问题,您可以通过使用的 json_last_error()。您可以添加的charset = UTF-8
的标题:
I think it's an encoding problem, you can verify this idea by using json_last_error(). You can add charset=utf-8
to the header :
$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
这篇关于json_en code不工作的PDO获取的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!