为了账号安全,请及时绑定邮箱和手机立即绑定

thinkphp5 返回json后没有length属性?

thinkphp5 返回json后没有length属性?

PHP
当年话下 2019-03-18 15:24:21
function findChild(&$arr,$id){ $childs=array(); foreach ($arr as $k => $v){ if($v['pid']== $id){ $childs[]=$v; } } return $childs; } function build_tree($rows,$root_id){ $childs=$this->findChild($rows,$root_id); if(empty($childs)){ return '[]'; } foreach ($childs as $k => $v){ $rescurTree=$this->build_tree($rows,$v['id']); if( null != $rescurTree){ $childs[$k]['data']=$rescurTree; } $childs[$k]['value'] = $v['id']; } return $childs; } public function test(){ $sql = db('auth_rule')->select(); $data = $this->build_tree($sql,0); return json($data) ; } 返回的json: [{ "id": 1, "name": "sys", "title": "系统设置", "type": 1, "status": 1, "condition": "", "pid": 0, "level": 0, "sort": 7, "data": [{ "id": 11, "name": "conf\/lst", "title": "配置列表", "type": 1, "status": 1, "condition": "", "pid": 1, "level": 1, "sort": 50, "data": [{ "id": 12, "name": "conf\/add", "title": "添加配置", "type": 1, "status": 1, "condition": "", "pid": 11, "level": 2, "sort": 50 }, { "id": 13, "name": "conf\/del", "title": "配置删除", "type": 1, "status": 1, "condition": "", "pid": 11, "level": 2, "sort": 50 }, { "id": 14, "name": "conf\/edit", "title": "配置编辑", "type": 1, "status": 1, "condition": "", "pid": 11, "level": 2, "sort": 50 }] }, { "id": 9, "name": "conf\/conf", "title": "配置项", "type": 1, "status": 1, "condition": "", "pid": 1, "level": 1, "sort": 50 }] }, { "id": 15, "name": "admin", "title": "管理员", "type": 1, "status": 1, "condition": "", "pid": 0, "level": 0, "sort": 50, "data": [{ "id": 16, "name": "admin\/lst", "title": "管理员列表", "type": 1, "status": 1, "condition": "", "pid": 15, "level": 1, "sort": 50, "data": [{ "id": 17, "name": "admin\/add", "title": "管理员添加", "type": 1, "status": 1, "condition": "", "pid": 16, "level": 2, "sort": 50 }, { "id": 18, "name": "admin\/del", "title": "管理员删除", "type": 1, "status": 1, "condition": "", "pid": 16, "level": 2, "sort": 50 }, { "id": 19, "name": "admin\/edit", "title": "管理员修改", "type": 1, "status": 1, "condition": "", "pid": 16, "level": 2, "sort": 50 }] }] }] 但是用js去获取res.length的时候,却提示cannot read property 'length' of undefined
查看完整描述

3 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

你这返回了个数组,不是json对象

查看完整回答
反对 回复 2019-03-18
?
慕标5832272

TA贡献1966条经验 获得超4个赞

cannot read property 'length' of undefined

的意思是undefined没有length属性,说明说你的resundefinedundefined当然没有length属性了。

为啥res会是undefined?不是在控制台里打印出来了吗?有两种可能,第一种是你打印的根本就不是同一个res.length(作用域的问题),第二种,也是我认为非常有可能的,就是你还没搞懂js的异步,前端在发请求的时候需要你提供一个“回调函数”,只有在这个回调函数里你才能获得res。比如

let res;
$.get(url, data => res = data);
console.log(res);  // undefined
res.length  // cannot read property 'length' of undefined

$.get(url, data => {
  console.log(data);
  console.log(data.length);
  // do something here
});
查看完整回答
反对 回复 2019-03-18
?
浮云间

TA贡献1829条经验 获得超4个赞

1)首先是楼主理解错误了,后端没有必要返回length长度这个变量
2)js直接获取一下数据的长度就解决了

查看完整回答
反对 回复 2019-03-18
  • 3 回答
  • 0 关注
  • 615 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信