资产管理系统按编码查询报错:SyntaxError: Unexpected end of JSON input
解决资产查询时的JSON解析错误(SQL返回空结果场景)
开发资产管理系统的资产编码查询功能时,遇到报错:
SyntaxError: Unexpected end of JSON input,查看Network面板发现SQL查询返回结果为空,此前未出现该问题。
错误原因分析
- PHP响应不完整:当请求的
opcion参数不等于'B'时,PHP代码没有输出任何内容,前端fetch尝试将空响应解析为JSON,直接触发语法错误。 - 查询结果格式不兼容:原PHP代码使用
fetch_all()默认返回索引数组,但前端代码尝试通过关联键名(如data[i].fecha)读取字段,会导致数据无法正常渲染;同时空查询结果未做明确标记,前端无法区分“无匹配数据”和“请求异常”。 - 前端错误处理缺失:未捕获JSON解析失败的场景,也没有对空数据做友好提示。
解决方案
1. 修复PHP代码,确保始终输出合法JSON
修改PHP逻辑,保证任何分支都输出标准JSON,并明确标记空结果:
<?php $value = $_POST['valor'] ?? ''; $op = $_POST['opcion'] ?? ''; // 默认返回空状态标记 $respuesta = array('respuesta' => 'invalid_request'); if ($op === 'B') { include '../modelo/conexiondb.php'; try{ $sql = $conexion->prepare('SELECT fecha, nombre as clasificacion, tipo_de_bien, concepto, cantidad, n_bien, n_control, nombre_y_descripcion, departamentos as departamento, v_unitario, estado as estatus from bienes INNER JOIN clasificacion on bienes.clasificacion=clasificacion.id_d INNER JOIN concepto_mov_incorporados on bienes.concep_mov=concepto_mov_incorporados.codigo INNER JOIN departamentos on bienes.departamento=departamentos.id_depa INNER JOIN estatus on bienes.estatus=estatus.id where n_bien=?'); $sql->bind_param('s', $value); $sql->execute(); // 获取关联数组,匹配前端键名访问需求 $result = $sql->get_result()->fetch_all(MYSQLI_ASSOC); if (!empty($result)) { $respuesta = $result; } else { // 标记无匹配数据 $respuesta = array('respuesta' => 'no_match'); } $sql->close(); $conexion->close(); }catch(Exception $e){ $respuesta = array('respuesta' => $e->getMessage()); } } // 设置JSON响应头,确保前端正确识别 header('Content-Type: application/json'); echo json_encode($respuesta); ?>
2. 修复JS代码,处理空结果与异常场景
完善前端逻辑,增加错误捕获和空数据提示:
const d = document; d.addEventListener('DOMContentLoaded', e => { detectarOpcion(); }); function detectarOpcion() { let $input = d.getElementById('valor'), $boton = d.getElementById('btn-buscar'); $boton.addEventListener('click', e => { e.preventDefault(); // 阻止按钮默认提交行为 let $select = d.getElementById('select').value; const datos = new FormData(); datos.append('valor', $input.value.trim()); // 去除输入首尾空格 datos.append('opcion', $select); fetch('./modelo/nbien_busqueda_y_ncontrol.php', { method: 'POST', body: datos, }) .then(res => { if (!res.ok) throw new Error(`请求失败,状态码:${res.status}`); // 捕获JSON解析错误 return res.json().catch(err => { throw new Error('响应格式错误,无法解析数据'); }); }) .then(data => { const $contenedor = d.querySelector('.contenedor-datatables'); const $tbody = d.querySelector('.tbody'); let respuesta = ''; // 处理不同状态的响应 if (data.respuesta === 'no_match') { respuesta = '<tr><td colspan="11">未找到匹配的资产</td></tr>'; } else if (data.respuesta === 'invalid_request') { respuesta = '<tr><td colspan="11">无效的查询类型</td></tr>'; } else if (Array.isArray(data) && data.length > 0) { // 遍历渲染有效数据 for(let item of data ){ respuesta += ` <tr> <td>${item.fecha}</td> <td>${item.clasificacion}</td> <td>${item.tipo_de_bien}</td> <td>${item.concepto}</td> <td>${item.cantidad}</td> <td>${item.n_bien}</td> <td>${item.n_control}</td> <td>${item.nombre_y_descripcion}</td> <td>${item.departamento}</td> <td>${item.v_unitario}</td> <td>${item.estatus}</td> </tr>`; } } $contenedor.classList.remove('none'); $tbody.innerHTML = respuesta; // 重新初始化DataTable,避免渲染异常 $('#bienes-busqueda').DataTable().destroy(); $('#bienes-busqueda').DataTable(); }) .catch(err => { console.error('查询错误:', err); const $contenedor = d.querySelector('.contenedor-datatables'); const $tbody = d.querySelector('.tbody'); $contenedor.classList.remove('none'); $tbody.innerHTML = `<tr><td colspan="11">查询失败:${err.message}</td></tr>`; }) .finally(() => { console.log('查询流程结束'); }) }) } $(document).ready(function(){ $('#bienes-busqueda').DataTable(); });
内容的提问来源于stack exchange,提问作者Kenlymar Paredes
相关产品推荐
相关产品推荐

