Tom*_*Tom 38
如果它只是一个正常的AJAX动作你将它从中返回,我想我过去在某个地方使用了以下内容:
return $this->renderText(json_encode($something));
Run Code Online (Sandbox Code Playgroud)
tim*_*dev 17
便宜的方式:
function executeSomethingThatReturnsJson(){
$M = new Model();
$stuff = $M->getStuff();
echo json_encode($stuff);
die(); //don't do any view stuff
}
Run Code Online (Sandbox Code Playgroud)
更聪明的方式:
更聪明的方法是创建一个很好的sfActions子类,帮助处理json-stuff.
在我最近做的一个项目中,我创建了一个名为'api'的应用程序(./symfony generate:application api)
然后创建一个文件,如:
API/LIB/apiActions.class.php
<?PHP
class apiActions extends sfActions {
public function returnJson($data){
$this->data = $data;
if (sfConfig::get('sf_environment') == 'dev' && !$this->getRequest()->isXmlHttpRequest()){
$this->setLayout('json_debug');
$this->setTemplate('json_debug','main');
}else{
$this->getResponse()->setHttpHeader('Content-type','application/json');
$this->setLayout('json');
$this->setTemplate('json','main');
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我在那里明确设置了模板.
所以我的jsonSuccess.php模板很简单:
<?PHP echo json_encode($data);
Run Code Online (Sandbox Code Playgroud)
虽然json_debugSuccess.php使事情更漂亮:
<?PHP var_dump($data); ?>
Run Code Online (Sandbox Code Playgroud)
然后你可以有一个控制器扩展apiActions(而不是通常的sfActions),如下所示:
<?php
class myActions extends apiAction {
public function executeList(sfWebRequest $request)
{
$params = array();
if ($request->hasParameter('id')){
$id = $request->getParameter('id');
if (is_numeric($id)){
$params['id'] = $id;
}
}
$data = Doctrine::getTable('SomeTable')->findAll();
$this->returnJson($data);
}
}
Run Code Online (Sandbox Code Playgroud)
免责声明:上面的代码是从我拥有的应用程序复制/粘贴,但简化.它仅用于说明目的 - 但它应该让您朝着正确的方向前进.
| 归档时间: |
|
| 查看次数: |
18780 次 |
| 最近记录: |