2014-05-09 122 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); 
    } 
}