我想知道如何在响应输出json数据后停止执行函数和其他控制器。
就我而言,
test()
controller dashboard
函数
dashboard
构造函数中将执行MY_Login
库MY_Login
库中会检查,是否是来自ajax的请求?如果是这样,只需将某些状态响应给ajax并停止执行test()
控制器中的dashboard
功能等其他功能。的Ajax
$.ajax({
type: "POST",
url: "dashboard/test",
async: false,
success: function(res){
//response data
}
});
控制器
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library("MY_Login");
}
public function index()
{
$this->load->view('admin/dashboard_view');
}
public function test(){
// must stop here...
$mydata = array(
"mydata" => "testing"
);
$this->output->set_content_type('application/json')->set_output(json_encode($mydata));
}
}
库
class MY_Login extends CI_Controller{
function __construct() {
parent::__construct();
// call with constructor.
$this->isLogin();
}
function isLogin() {
// if there is no session existed
if(!$this->session->userdata('USR_NM')){
if($this->input->is_ajax_request()){
$redirect_link = array(
"ajax_redirect_link" => TRUE
);
$this->output->set_content_type('application/json')->set_output(json_encode($redirect_link));
// what i want...
// just response the above json data to ajax
//and stop execute other code below or other controller
}else{
// redirect to login page
redirect('/login', 'refresh');
}
}
}
}
答案 0 :(得分:1)
如果你想每次都想做同样的事情,你可以这样做:
图书馆:
if($this->input->is_ajax_request())
{
$redirect_link = array("ajax_redirect_link" => TRUE);
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($redirect_link));
exit;
}