dpqg86714 2017-10-24 04:48
浏览 46

为什么我的脚本忽略空数组结果?

I have a script that basically check if there is a result from a query:

$.post('<?php echo site_url('xxx/yyy'); ?>',{data:no},function(result){
        if(!result){
            alert("No Data");
        }
        else{
            alert("Data retrieved");
        }
});

Why my IF alert Data retrieved when I get empty JSON array. I tried to do alert(result) with different data (the data which result is empty and result is true), but both data is alerting Data retrieved.

This is my model:

$this->db->select('*',FALSE);
    $this->db->from('t_penomoran tp');      
    $this->db->join('t_penomoran_detail t_pd', 'tp.nomor = t_pd.nomor');

    $this->db->where('tp.nomor',$nomor);

    $query = $this->db->get();
    return $query->result_array();

note:
For some reason when I do alert(result.length) with data that has no value, the result is 2. But when I do alert(result) with data that has no value the result is []

  • 写回答

3条回答 默认 最新

  • dongmao4486 2017-10-24 04:51
    关注

    Empty array is a truthy value, meaning in your if statement, it will evaluate to true and that is why you see the alert(). To fix it, use the length property:

    if(!result.length) alert('no data')
    
    评论

报告相同问题?