有没有具体的演示或示例代码,我知道的,所以希望这些提示将帮助您开始使用它...
这是可能的,而且比较容易,接受AJAX请求,并产生JSON对Kohana的回应。首先要注意的是,除非特别指出,Kohana的将总是尝试生成视图,首先会失败,因为一个JSON响应,以便第一件事:
if ($this->request->is_ajax()) {
// Disable any rendering of the template so it just returns json.
$this->auto_render = FALSE;
}
你可能会想把它放在before()方法中,可能是父控制器,以便它在从数据库获取数据之前始终运行。
我个人喜欢这样的事情是建立一个标准的AJAX响应数组,以便数据总是以相对标准的格式返回。示例:
// Standard ajax response array.
$this->ajax_response = array(
'success' => FALSE,
'error' => NULL,
'raw_data' => NULL,
'generated' => ''
);
自定义上述以符合您的要求的用法。你可能也想在你的before()方法中使用它。
现在在您的操作方法中,从数据库中获取数据并将其添加到数组中。
public function action_foobar() {
// Get the primary key ID from the URL.
$var1 = $this->request->param('var1');
$data = ORM::factory('Model', $var1);
if ($data->loaded()) {
$this->ajax_response['success'] = TRUE;
$this->ajax_response['raw_data'] = $data;
} else {
$this->ajax_response['error'] = 'Data could not be found.';
}
}
然后,您应该能够通过调用一个网址,如http://www.website.com/controller/foobar/42
的最后一块拼图真的返回这个数据来请求这个数据,此刻的Kohana不会输出任何东西,因为我们已经告诉它不要。在你()方法之后,请执行下列操作:
if ($this->request->is_ajax()) {
$this->request->headers('Content-Type', 'application/json');
$this->response->body(json_encode($this->ajax_response));
}
然后你可以自由地诠释这种反应,但是你在jQuery的看适合你的客户端应用程序:
$.ajax({
type: "POST",
url: "http://www.website.com/controller/foobar/" + foobarId,
dataType: 'json',
success: function (data) {
if (!data.success) {
alert(data.error);
} else {
// Handle the returned data.
}
},
error: function (xhr, status, errorThrown) {
// Something went very wrong (response failed completely).
alert(errorThrown);
}
});
好运与建立你的应用程序!我希望这有助于至少让你开始。