如果构造函数中的验证失败,我正在尝试阻止方法执行。我正在使用AJAX,我将请求发送到example/search
这样的网址。我目前正在检查变量是否不是假的,但我认为有更好的方法可以做到这一点,不是吗?
class Example extends CI_Controller {
public $error;
function __construct() {
parent::__construct();
//validation rules
if($this->form_validation->run() == FALSE) {
$this->error=1;
}
}
function search() {
if(!$this->error) {
//code
}
}
}
答案 0 :(得分:1)
<强>应用/配置/ form_validation.php 强>
$config = array(
'search' => array(
array('field'=>'', 'label'=>'', 'rules'=>''),
array('field'=>'', 'label'=>'', 'rules'=>'')
),
);
-
<强>控制器强>
public function search(){
//is ajax request?
if( !$this->input->is_ajax_request() )
{
return show_error('Bad Request!'); // bye bye, stop execution
}
$this->output->set_status_header('200');
if( ! $this->form_validation->run('search') )
{
echo json_encode(array(
'error' => 1,
'errors' => array(
'field' => form_error('field')
)
));
return; // bye bye, stop execution
}
//all good, continue executing
//.....
}
修改强>
//For just a constructor
protected $isValidated = TRUE;
public function __construct(){
//check for valid ajax request
//do this in parent class(ajax_controller) ?
if( !$this->form_validation->run('search') )
{
$this->isValidated = FALSE;
return echo json_encode( array('error' => 1));
}
if($isValidated)
{
$this->_search( $this->input->post() );
}
}
protected function _search( $input ){}
-
class Ajax_Controller extends CI_Controller{
public function __construct(){
if( !$this->input->is_ajax_request() )
{
return show_error('Bad Request!');
}
$this->output->set_status_header('200');
}
}