所以我的问题是:
我正在我的数据库中获取数据,并希望在jSON format中提供它们。
我的controller如下:
public function testAction()
{
$articles = Article::find();
if (count($articles) > 0) {
$final_array = array();
foreach ($articles as $article) {
$user = Users::find("id = " . $article->getUsersId());
$current = array('id' => $article->getId(),
'name' => $article->getName(),
'replies' => $article->getReplies(),
'date' => $article->getDate(),
'illustration' => $article->getIllustration(),
'content' => $article->getContent(),
'link' => $article->getLink(),
'user_id' => $article->getUsersId(),
'user_name' => $user[0]->getPseudo());
$final_array[] = $current;
}
$result = array('status' => 1,
'message' => 'article have been downloaded',
'response' => $final_array);
} else {
$result = array('status' => 1,
'message' => 'no article in the stack');
}
$this->view->disable();
$this->response->setContentType('application/json', 'UTF-8');
echo json_encode($result);
}所显示视图提供了nothing
<html>
<head></head>
<body></body>
</html>问题不是来自我的模型或SQL请求,因为如果我像这样改变我的控制器来var_dump我的结果:
[...]
//$this->view->disable();
//$this->response->setContentType('application/json', 'UTF-8');
var_dump($result);
[...]它为我提供了以下内容(长度并不总是匹配的,因为我自愿更改了在这种情况下不感兴趣的内容):
array (size=3)
'status' => int 1
'message' => string 'article have been downloaded' (length=28)
'response' =>
array (size=1)
0 =>
array (size=9)
'id' => string '1' (length=1)
'name' => string 'Champion de CAPU' (length=16)
'replies' => string '0' (length=1)
'date' => string '2014-06-10 06:22:35' (length=19)
'illustration' => string 'illustration_link' (length=69)
'content' => string 'content_text' (length=182)
'link' => string 'more_link' (length=50)
'user_id' => string '6' (length=1)
'user_name' => string 'bathiatus' (length=9)这就是我想要的..。
此外,我实际上在另一个controller中做了同样的事情,以便提供所有的用户(比如UserController,jGetAllUsersAction),它工作得很好(代码是相同的,只是数据库中的表不同)。
发布于 2014-06-13 09:19:51
我终于找到了问题所在。
谢谢你的回答,我发现所有有目的的显示视图的方法都是有效的(包括我在问题中的目的)。
我真的不知道哪种方法是最好的,但我猜我问题中的那个不是。
顺便说一下,问题是我试图注入special characters (比如é、è、à、ë等)在我的Json object里。事实上,我的内容是法语的。
Json对象不支持这些类型的字符,而使用var_dump打印它们没有问题。
发布于 2014-06-11 21:17:15
如果你只想要一个json响应,你可以在你的控制器中这样做:
return $this->response->setJsonContent($result);
Phalcon禁用视图并自动设置正确的内容类型。json_encode也已经完成了,所以只需放入$result即可。
发布于 2014-06-10 19:58:33
默认情况下,Phalcon需要一个视图来返回响应(在本例中是JSON)。
控制器代码:
$this->response->setContentType('application/json', 'UTF-8');
$this->view->setVar("some_var", $result);然后,您必须创建一个与控制器名称和函数名称相对应的视图,并将其放入:
<?php echo json_encode($some_var); ?>如果您不想创建其他视图,请使用此链接以供进一步参考:
http://docs.phalconphp.com/en/latest/reference/response.html
https://stackoverflow.com/questions/24132710
复制相似问题