Sha*_*eer 10 php kohana kohana-3
我正在Kohana框架中开发一个应用程序.我想知道在kohana中实现ajax的最佳实践.到目前为止,我正在为ajax使用不同的控制器.我认为重要的问题是最小化资源需求和处理会话.
提前致谢
Enr*_*que 11
我正在使用这个:
在Controller_Template中:
public function before()
{
$this->auto_render = ! $this->request->is_ajax();
if($this->auto_render === TRUE)
{
parent::before();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的行动中:
if ($this->request->is_ajax())
{
...
$this->response->headers('Content-type','application/json; charset='.Kohana::$charset);
$this->response->body($jsonEncoded);
}
Run Code Online (Sandbox Code Playgroud)
正如上面提到的那样,你不需要为你的ajax动作单独的控制器.您可以利用Kohana的请求对象来识别请求类型.这可以通过以下方式完成:
<?php
class Controller_Test extends Controller_Template {
/**
* @var View Template container
*/
protected $template = 'template';
/**
* @var View Content to render
*/
protected $content = 'some/content/view';
// Inherited from parent class
protected $auto_template_render = TRUE;
public function before()
{
parent::before();
if ($this->request->is_ajax() OR !$this->request->is_initial()) {
$this->auto_template_render = FALSE;
}
}
public function after()
{
if ($this->auto_template_render == FALSE) {
// We have ajax or internal request here
$this->template = $this->content;
} else {
// We have regular http request for a page
$this->template = View::factory($this->template)
->set('content', $this->content);
}
// Call parent method
parent::after();
}
}
Run Code Online (Sandbox Code Playgroud)
虽然示例非常简单,但可以根据您要归档的内容进行改进.基本上我已经完成了自己编写我Controller_Template需要的东西.您也可以考虑将格式参数添加到您的网址,以便.html网址返回数据的常规html表示,.json网址也是如此,但是采用json格式.有关更多信息(可能是想法),请参阅kerkness非官方Kohana wiki
| 归档时间: |
|
| 查看次数: |
7444 次 |
| 最近记录: |