【发布时间】:2014-06-10 04:10:56
【问题描述】:
这是我的问题:
我正在我的数据库中获取数据并希望在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)并且它工作得很好(除了数据库中的表之外,代码是相同的不同)。
【问题讨论】:
-
我对 Phalcon 一无所知,但从使用
$this切换到echo似乎很可疑。 -
@Ignacio Vazquez-Abrams:
$this->view->disable();在我的视图中禁用 html 内容(我使用它是为了取消我的“默认模板”);$this->response->setContentType('application/json', 'UTF-8');设置视图的内容类型(所以是application/json,因为我要显示json数据)。然后回声在我看来只是显示了一些东西。我不知道这种方式是否是好方法,但它在我的其他视图(与其他控制器)中的相同结构中运行良好。