2013-05-06 68 views
0

我正在使用CodeIgniter中的AJAX。如果數據庫中的數據不匹配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」。

回答

1

,你可以改變你的控制器,如:

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

嗨感謝您的答覆,但是這也沒有工作:(我覺得有點毛病模型,因爲我沒有收到來自其他的任何數據 – 2013-05-06 11:28:38

+0

我無法通過瀏覽器控制檯來追蹤問題 – 2013-05-06 11:30:41

+0

嘿它現在的作品:) – 2013-05-06 11:35:07

相關問題