403 CodeIgniter中使用Ajax的禁止错误

时间:2018-06-19 17:39:18

标签: php codeigniter codeigniter-3

我正在使用ajax在textbox自动完成中显示名字,但是我的ajax URL无法正常工作。每次在“网络”标签中显示

  

403禁止。

我尝试过这样的ajax URL

 url:baseUrl + "/index.php/Employee_control/search_with_emp_name",
 url:baseUrl +"/Employee_control/search_with_emp_name",

但仍然显示相同的错误。

我的.htaccess代码

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

我的基本URL $config['base_url'] = 'http://localhost/test/';

我的观点

<input type="text" class="form_control" name="employee_name" id="employee_name">

custome.js

var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];


    $(document).ready(function() {
       $("#employee_name").keyup(function() {
           var emp_name = $('#employee_name').val();
              $.ajax({
                   type: "POST",
                   url:baseUrl + "/index.php/Employee_control/search_with_emp_name",
                   data: {
                      emp_name: emp_name
                   },

                   success: function(html) {
                      alert(html);
                   }
               });
            });
    });

控制器

public function search_with_emp_name(){
        echo $emp_name = $this->input->post('emp_name');
       $get_result=$this->Employee_model->search_emp_name($emp_name);
       print_r($get_result);
}

模型

public function search_emp_name($emp_name){
          $this->db->like('firstname', $emp_name, 'both'); 
          $query = $this->db->get('tbl_employee');
          $result = $query->result();
        if($result)
            {
              return $result;
            }
            else 
            {
              return 0;
            } 

}

1 个答案:

答案 0 :(得分:4)

希望这对您有帮助:

首先请确保您已在config.php中将csrf令牌设置为false;

 $config['csrf_protection'] = FALSE;
 $config['csrf_token_name'] = 'csrf_test_name';
 $config['csrf_cookie_name'] = 'csrf_cookie_name';

或者,如果您不想将其设置为false,则只需将csrf_token_nameget_csrf_hash与ajax调用中的数据一起传递 像这样:

 data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>'},

您的基本网址似乎有问题,因此将这一行代码放在页面标题中,然后像这样使用BASE_URL

<script type="text/javascript">
     const BASE_URL = "<?php echo site_url();?>";
</script>
<script src="<?=site_url('your-js-path/js/custome.js');?>"></script>

您的ajax应该是这样的:

$(document).ready(function() {
       $("#employee_name").keyup(function() {
           var emp_name = $('#employee_name').val();
              $.ajax({
                   type: "POST",
                   url: BASE_URL+"Employee_control/search_with_emp_name",
                   data: {emp_name: emp_name},

                   success: function(html) {
                      alert(html);
                   }
               });
            });
    });
相关问题