如果数据库中的数据不匹配,Codeigniter Ajax不会返回任何错误消息


Codeigniter Ajax not returning any error message if the data is not matched in database

我正在CodeIgniter中使用AJAX。

这是我的代码。当我的SQL查询返回结果时,这是工作的。如果查询为空,则AJAX不返回任何内容。

我的模型:

function view_filter_by_cat($id){
$sql = "SELECT * FROM ".TBL_FILTER_OPTION." WHERE FID=?";
$query=$this->db->query($sql,$id);
if($query->num_rows()){
    foreach ($query->result() as $row){
        $result[] = $row;
    }           
    $query->free_result();
    return $result;         
}
AJAX控制器:

public function find_filters_options(){
    if($this->input->post('FID')){
        $fid = $this->input->post('FID');
        $filterList= $this->filter_option_model->view_filter_by_cat($fid);          
        if($this->filter_option_model->view_filter_by_cat($fid)){               
            echo (json_encode($filterList));
        }else{              
            echo '0';
        }
    }
}
Ajax调用:

$.ajax({
    type: "POST",
    url: '<?php echo site_url('admin/products/find_filters_options'); ?>',
    data: {
        <?php echo $this->security->get_csrf_token_name(); ?> : '<?php echo $this->security->get_csrf_hash(); ?>',
        FID: fid
    },
    success: function(data1){
        alert(data1);
    }
});

我的问题是,当查询不返回任何值时,我无法访问成功消息。当返回值为空时,我想获得值'0'。

你可以把你的控制器改成:

public function find_filters_options(){
  $result = array();
    if($this->input->post('FID')){
        $fid = $this->input->post('FID');
        $filterList= $this->filter_option_model->view_filter_by_cat($fid);          
        if($this->filter_option_model->view_filter_by_cat($fid)){               
            $result["got_data"] = "yes";
            $result["data"] = $filterList;            
        }else{              
            $result["got_data"] = "no";
        }
    }
    else {
      $result["got_data"] = "no";
    }
    echo (json_encode($result));
}

和jquery ajax

$.ajax({
  type: "POST",
  url: '<?php echo site_url('admin/products/find_filters_options'); ?>',
  data : {<?php echo $this->security->get_csrf_token_name(); ?> : '<?php echo 
$this->security->get_csrf_hash(); ?>', FID : fid },
  dataType: "json",
  success: function(data1) {
    if(data1.got_data == "yes") {
        var data = data1.data; //get data from server here
    } 
    else {
       //dont have any data
       //show some appropriate message
    }
  }
});