2011-04-06 65 views
10

我正在Kohana框架中开发应用程序。我想知道在kohana中实现ajax的最佳实践。到目前为止,我为ajax使用了不同的控制器。我认为重要的关注点将是尽量减少资源需求和处理会议。Kohana框架 - Ajax实现最佳实践

在此先感谢

回答

11

我使用这个:

在Controller_Template:

public function before() 
    { 
     $this->auto_render = ! $this->request->is_ajax(); 
     if($this->auto_render === TRUE) 
     { 
      parent::before(); 
     } 
    } 

而且我的行动中:

 if ($this->request->is_ajax())  
     { 
      ...   
      $this->response->headers('Content-type','application/json; charset='.Kohana::$charset); 
      $this->response->body($jsonEncoded); 
     } 
+2

这是很好..我一定会利用这个...谢谢..无论如何,我期待更多的建议,这将有助于整个社区.. – Shameer 2011-04-10 18:11:00

1

你并不真的需要一个单独的控制器,可以使用Kohana_Controller_Template处理AJAX请求以及。

你决定在AJAX请求(或者子请求,通常是相同的)的情况下,响应是什么。我通常只在请求是最初的模板(而不是ajax)的情况下实际渲染模板,否则将其渲染为$ content var。

此外,您还可以轻松地检查如果请求是AJAX /子请求:

if ($request->is_ajax()) 
if (! $request->is_initial()) 
+0

我所有的控制器扩展Controller_DefaultTemplate扩展Kohana_Controller_Template。我在我的DefaultTemplate的before()方法中分配了很多东西,这通过ajax请求时不是必需的。所以我决定为ajax请求使用不同的控制器,即使它扩展了Kohana_Controller_Template。希望这使得sence。 – Shameer 2011-04-08 04:16:23

1

此外,如果使用Kohana_Controller_Template作为控制器的父/祖先这是好事,记得要禁用自动渲染通过AJAX访问时,以防止加载和呈现整个模板。

if ($request->is_ajax()) $this->auto_render = FALSE; 
5

就像上面说的家伙,你不需要一个单独的控制器为您的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(); 
    } 
} 

尽管示例非常简单,但它可能会改进为您要存档的内容。基本上我已经完成编写我自己的Controller_Template做我需要的东西。您也可以考虑将格式参数添加到您的网址,以便.html网址返回数据的常规html表示形式,.json网址也采用相同的格式,但采用json格式。 欲了解更多信息(也可能是想法),请参阅kerkness unofficial Kohana wiki