2014-05-09 40 views
2

我对Kohana/php的世界很陌生,并且在理解如何获得ajax请求的结果时遇到了一些问题。该请求正在通过单击操作进行调用,并且正在调用以下方法。Kohana与AJAX获取请求

function addClickHandlerAjax(marker, l){ 
    google.maps.event.addListener(marker, "click",function(){ 
    console.log(l.facilityId); 
    removeInfoWindow(); 
    //get content via ajax 
     $.ajax({ 
     url: 'map/getInfoWindow', 
     type: 'get', 
     data: {'facilityID': l.facilityId }, 
     success: function(data, status) { 
     if(data == "ok") { 
      console.log('ok'); 
     } 
     }, 
     error: function(xhr, desc, err) { 
     console.log(xhr); 
     console.log("Details: " + desc + "\nError:" + err); 
     } 
    }); // end ajax call 

}); 
} 

在我的控制器我有一个方法

 public function action_getInfoWindow(){ 

     if ($this->request->current()->method() === HTTP_Request::GET) { 

     $data = array(
      'facility' => 'derp', 
     ); 

     // JSON response 
     $this->auto_render = false; 
     $this->request->response = json_encode($data); 

    } 
    } 

我看到提琴手HTTP请求,并通过正确的facilityID参数。不过,我正在关于如何将所有碎片连接在一起的一些断开。

回答

3

要发送回应浏览器,您应该使用Controller::response而不是Controller::request::response。所以你的代码应该是这样的:

public function action_getInfoWindow() { 
    // retrieve data 
    $this->response->body(json_encode($data)); 
} 

这应该给你一些输出。

查看Documentation了解更多详细信息。

编辑

,你可以做些什么,让你的生活更容易一点,特别是如果你要使用AJAX请求了很多,是创建Ajax控制器。你可以将所有检查和变换填入其中,而不再担心它。示例控制器可能如下所示。还可以查看Kohana发布的Controller_Template

class Controller_Ajax extends Controller { 
    function before() { 
     if(! $this->request->is_ajax()) { 
      throw Kohana_Exception::factory(500, 'Expecting an Ajax request'); 
     } 
    } 

    private $_content; 

    function content($content = null) { 
     if(is_null($content)) { 
      return $this->_content; 
     } 
     $this->_content = $content; 
    } 

    function after() { 
     $this->response->body(json_encode($this->_content)); 
    } 
} 

// example usage 
class Controller_Home extends Controller_Ajax { 
    public function action_getInfoWindow() { 
     // retrieve the data 
     $this->content($data); 
    } 
}