In CodeIgniter, all requests generally correspond to a function in a controller, and if you have a different request, such as Ajax and a normal request, the returned items will generally differ, such as This->load->view or direct echo.
Two ways to write together makes me feel particularly uncomfortable, I envision a solution is to use the HTTP header in the accept, how to produce a way, is in a function, different requests output different view styles, such as the AJAX request this function, return JSON format, ordinary request, The HTML is returned. I would like this effect, how to do just fine.
Reply content:
In CodeIgniter, all requests generally correspond to a function in a controller, and if you have a different request, such as Ajax and a normal request, the returned items will generally differ, such as This->load->view or direct echo.
Two ways to write together makes me feel particularly uncomfortable, I envision a solution is to use the HTTP header in the accept, how to produce a way, is in a function, different requests output different view styles, such as the AJAX request this function, return JSON format, ordinary request, The HTML is returned. I would like this effect, how to do just fine.
Ajax request a disk to return JSON data, not directly to the HTML, and view is a direct include view, the principle is different, if you want to this kind of, then customize the View method:
public function loadView($view, $data) { if( $this->input->is_ajax_request() ) { echo $this->load->view($view, $data, TRUE); exit; } // 如果是 ajax 不会执行到这里 $this->load-
< code="">
以后你载入 view 时,使用 $this->loadView($viewName, $data) 而不再使用 $this->load->view(); 即可,这个 loadView 方法你可以写在父 Contrller 里面,这只是思路,你可以按需求来定制!
already provided CodeIgniter () in the input class of is_ajax_request () method to determine if an AJAX request is made, and can be invoked in the form of $this->input->is_ajax_request ().
See http://codeigniter.org.cn/user_guide/libraries/input.html.
First of all, according to the "single functional Principle", it is not recommended that you design a feature like this. You can encapsulate the main function as a callable method, and then call this method in different controllers to handle it. In addition, JSON is also a form of view, so you can completely transfer the data into the view, just two different view, one is the HTML display, one is the JSON display
Why not add a request parameter to the request to differentiate the terminal?
It can't be separated by UA.
Define (' is AJAX ', Isset ($ server[' HTTP X requested with ']) && strtolower ($ server[' HTTP X requested_with ']) = = ' XMLHttpRequest ') ;
When judging this if (Is_ajax) {... }else {... }