先添加一行简单的代码,在ci里定义ajax的请求。
在application/config/constants.php 添加如下:
// Define Ajax Request
define(‘IS_AJAX’, isset($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && strtolower($_SERVER[‘HTTP_X_REQUESTED_WITH’]) == ‘xmlhttprequest’);
在控制器里就可以判断是否是Ajax的请求,从而决定是否load view。
public function test(){
if(IS_AJAX){
$this->load->view(‘ajax_test’);
}else{
echo ‘Direct access not allowed!’;
// or load other view file.
//$this->load->view(’test’);
}
}
Codeigniter里在登录后使用Ajax的简单方式.如果没有登录,发送401。
public function secure(){
if(! $this->session->userdata(’logged_in’)){
header(‘HTTP/1.1 401 Unauthorized);
}
//other code...
}
再在js做判断跳转:
$().ajaxError(function(xhr,status,err){
if(status.status == 401){
window.location.href=’/login’;
}
});