How to stop execute other controller after respons

2019-03-06 14:17发布

问题:

I want to know how to stop execute function and other controller that involved after we response output json data.

In my case here,

  1. I just call test() function in dashboard controller
  2. In dashboard constructor will execute MY_Login library
  3. In MY_Login library will check that, Is it request from ajax? if so, just response some status to ajax and stop execute others such as test() function in dashboard controller.

Ajax

$.ajax({
    type: "POST",
    url: "dashboard/test",
    async: false,
    success: function(res){
        //response data
    }
});

Controller

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));
    }
}

Library

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');
            }
        }
    }
}

回答1:

HI if every time you want to do the same thing as you said you can do that :

Library :

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;
}