Framework7 v2获取JSON数据时ID值返回undefined求助
问题:从返回的JSON数据中提取ID值时控制台返回undefined
我有如下JSON数据:
[ { "ID": 000, "pass_Word": "abc" } ]
我想从中提取ID的值,当前使用的代码如下:
var Data = {"User_ID" : login_id, "password" : password}; JSON.stringify(Data); app.request.post('http://URL?type=json', Data , function (data) { console.log(data.ID); });
执行代码后控制台返回undefined,请求协助解决。
解决方案
看起来问题出在这几个地方,咱们一步步来解决:
返回的
data是数组而非单个对象
你提供的原始JSON数据是一个数组(外层包裹了[]),而不是单独的对象。数组本身没有ID属性,直接访问data.ID自然会返回undefined。你需要先取数组里的第一个元素,再访问它的ID:console.log(data[0].ID);确认
data是否已经被解析为JSON对象
有些请求库不会自动把返回的字符串解析成JSON对象,这时候你得手动做解析操作。可以在回调函数里先处理数据:app.request.post('http://URL?type=json', Data , function (response) { const data = JSON.parse(response); // 先把响应字符串解析成JSON对象 console.log(data[0].ID); // 再取数组第一个元素的ID });额外检查:
JSON.stringify(Data)的使用是否有效
你代码里调用了JSON.stringify(Data)但没把结果赋值给变量,这行代码其实没起到任何作用。如果你的app.request.post要求发送JSON格式的请求体,应该把字符串化后的值传进去:var Data = {"User_ID" : login_id, "password" : password}; const jsonData = JSON.stringify(Data); // 把字符串化的结果存到变量里 app.request.post('http://URL?type=json', jsonData , function (response) { const data = JSON.parse(response); console.log(data[0].ID); });
把这些调整后,应该就能正确获取到ID的值了。
内容的提问来源于stack exchange,提问作者Rahul Saxena
相关产品推荐
相关产品推荐

