使用PHP从SQL源输出Grid失败,JSON解码错误及索引未定义求助
让我们逐个解决你遇到的问题:
1. 修复「Undefined index: id」错误
这个Notice的原因很直接:你的SQL查询语句里只选取了firstname, lastname, title, businessunit, experience这几个字段,完全没包含id字段,所以$row['id']根本不存在,自然会抛出索引未定义的提示。
解决方式二选一:
- 如果你确实需要
id字段,修改SQL查询,把id加进去:select id, firstname, lastname, title, businessunit, experience from employee_tab order by businessunit - 如果不需要
id字段,直接从数组里删掉'id'=>$row['id'],这一行即可。
2. 解决Ext.JSON.decode()无效JSON错误
你在空数据分支输出的(success:true,"error":0)是非法JSON格式:JSON要求用大括号{}包裹对象,而且所有键名必须用双引号包裹。这种格式错误直接导致ExtJS无法解析返回值。
把错误分支的输出改成标准JSON:
echo '{"success":true,"error":0}';
另外建议提前初始化$myArray,避免变量未定义的判断,代码会更简洁健壮。
3. 处理WAI-ARIA的IMG alt属性提示
这个提示来自前端Grid组件,说明你Grid里的某个图片列对应的<img>标签缺少alt属性,不符合无障碍访问规范。
解决方法是在ExtJS的Grid列配置里补充alt属性:
- 如果用的是
imagecolumn类型,直接设置altText:{ xtype: 'imagecolumn', dataIndex: 'yourImageField', altText: '员工头像' // 可以根据需求设置静态或动态文本 } - 如果是自定义渲染器生成图片,手动给
<img>标签加上alt属性:{ text: '头像', renderer: function(value) { return `<img src="${value}" alt="员工头像">`; } }
修改后的完整PHP代码
<?php require_once "../../_includes/headers.php"; // 补充id字段(如果需要) $query = "select id, firstname, lastname, title, businessunit, experience from employee_tab order by businessunit"; logit($query); $result = odbc_exec($connection,$query); $myArray = []; // 提前初始化数组,避免未定义问题 while($row = odbc_fetch_array($result)) { $myArray[] = array( 'id'=>$row['id'], 'firstname'=>$row['firstname'], 'lastname'=>$row['lastname'], 'title'=>$row['title'], 'businessunit'=>$row['businessunit'], 'experience'=>$row['experience'], ); } if (sizeof($myArray) > 0) { echo json_encode($myArray); } else { // 输出标准合法的JSON echo '{"success":true,"error":0}'; } ?>
内容的提问来源于stack exchange,提问作者Joel Deslauriers
相关产品推荐
相关产品推荐

