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

Codeigniter中AJAX返回HTML却解析JSON引发报错问题排查

问题根源与解决方案

你遇到的这两个错误,核心原因是前端和后端的数据格式完全不匹配,咱们一步步拆解问题,再给出可行的修复方案:

为什么会报错?

  1. JSON解析失败:后端直接输出的是HTML格式的<option>标签,但你在前端success回调里强行用JSON.parse(result)去解析它——HTML字符串根本不是合法的JSON,所以必然抛出Uncaught SyntaxError: Unexpected token < in JSON at position 0。
  2. 遍历无效数据:当JSON.parse失败后,$.each试图去遍历一个无效的结果,就会触发Cannot use 'in' operator to search for 'length' in的错误。

再看代码里的矛盾点:

  • 前端AJAX的dataType设为了"html",说明你预期后端返回HTML,但后续却把HTML当成JSON去解析,逻辑完全冲突。
  • 后端Controller直接echo输出option标签,返回的是纯HTML,但前端却错误地尝试把它转成JSON对象遍历。

修复方案(两种可选)

方案1:后端返回JSON数据,前端动态渲染Option(更规范)

这种方式前后端职责更清晰,也便于后续扩展。

修改Controller代码

不再直接输出HTML,而是把燃料数据整理成结构化的JSON返回:

public function getFuel($modelid, $variant) {
    $this->load->model('M_address');
    $fuel = $this->M_address->getFuel($modelid,$variant);
    $fuel_list = array();
    foreach ($fuel as $fuels) {
        array_push($fuel_list, $fuels->fuel);
    }
    $fuel_list = array_unique($fuel_list);
    
    // 整理成包含value和文本的结构化数组
    $options = [];
    foreach($fuel_list as $fuel) {
        $ts = explode('/', $fuel);
        foreach($ts as $tt) {
            $options[] = [
                'value' => $fuel,
                'text' => $tt
            ];
        }
    }
    
    // 设置响应头为JSON格式,返回数据
    header('Content-Type: application/json');
    echo json_encode($options);
}

修改前端AJAX代码

把dataType改为json,遍历JSON数据生成option:

function getFuel() {
    var getVariant = $('#variant').val();
    var car_model = $('#car_model').val();
    console.log("this is inside get Fuel");
    console.log(car_model);
    console.log(getVariant);
    $.ajax({
        url: "<?php echo base_url() ?>pms1/getFuel/" + car_model + "/" + getVariant,
        dataType: "json", // 明确预期JSON格式
        success: function(result) {
            $('#fuel').html('<option>SELECT</option>');
            // 遍历JSON数组,逐个添加option
            $.each(result, function(index, item) {
                $('#fuel').append(`<option value="${item.value}">${item.text}</option>`);
            });
        },
        error: function(xhr, status, error) {
            // 添加错误处理方便调试
            console.error('AJAX请求出错:', error);
        }
    });
}

方案2:保持后端返回HTML,前端直接插入(更简单)

如果不想改动后端的输出逻辑,只需要修改前端,直接把返回的HTML插入到select中:

function getFuel() {
    var getVariant = $('#variant').val();
    var car_model = $('#car_model').val();
    console.log("this is inside get Fuel");
    console.log(car_model);
    console.log(getVariant);
    $.ajax({
        url: "<?php echo base_url() ?>pms1/getFuel/" + car_model + "/" + getVariant,
        dataType: "html",
        success: function(result) {
            // 直接清空原有内容,添加默认选项+后端返回的HTML
            $('#fuel').html('<option>SELECT</option>' + result);
        },
        error: function(xhr, status, error) {
            console.error('AJAX请求出错:', error);
        }
    });
}

额外小修复

你的Model代码里,getFuel函数的print_r($result->result());永远不会执行——因为return $result->result();已经终止了函数,建议删掉这行多余代码,避免意外输出干扰返回结果。

内容的提问来源于stack exchange,提问作者BILAL MALIK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:22:36