You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter中Ajax调用无数据时,如何在select选项显示data not found

解决CodeIgniter中Ajax无数据时显示提示文本的问题

现有CodeIgniter项目中,state下拉框切换会触发Ajax请求调用suppliers/get_city接口获取城市数据并渲染到city下拉框,功能正常。需要实现:当Ajax返回无数据时,在city下拉框中显示data not found选项。

修改后的JS代码

<script type="text/javascript">
    $(document).ready(function(){
        $('#state').change(function(){ 
             var id=$(this).val();
            $.ajax({
                url : "<?php echo base_url('suppliers/get_city');?>",
                method : "POST",
                data : {id: id},
                async : true,
                dataType : 'json',
                success: function(data){  
                    var html = '';
                    // 判断返回数据是否为空
                    if(data.length === 0){
                        html = '<option value="">data not found</option>';
                    } else {
                        var i;
                        for(i=0; i<data.length; i++){
                            html += '<option value='+data[i].id+'>'+data[i].city_name+'</option>';
                        }
                    }
                    $('#city').html(html);
                },
               error: function(jqXHR, textStatus, errorThrown){
                  alert('Error: ' + textStatus + ' - ' + errorThrown);
               }
               });
            return false;
        }); 
    });
</script>

修改说明

  • 在success回调函数中新增数据长度判断:当返回的data数组长度为0时,直接生成包含data not found的选项
  • 保留原有循环逻辑处理有数据的场景,确保正常渲染城市列表
  • 通过$('#city').html(html)覆盖下拉框原有内容,保证每次切换都能正确更新显示内容

内容的提问来源于stack exchange,提问作者Shivendra Kr. Sahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:40:22