如何从AJAX响应中获取ResCode?取值返回undefined该如何解决
问题根因
你接口返回的data.data.response是JSON格式的字符串,不是可直接读取属性的JavaScript对象,直接对字符串取属性自然会返回undefined。你可以先执行console.log(typeof data.data.response)验证,输出结果会是string。
解决方法
先调用JSON.parse()方法把这个字符串解析为JavaScript对象,再读取对应字段即可,修改后的代码如下:
success: function (data) { // 解析response字符串为对象 const responseData = JSON.parse(data.data.response); // 读取目标字段 console.log(responseData.ResStatus); console.log(responseData.ResCode); },
可选优化
如果接口可能返回异常格式的字符串,建议加个try-catch捕获解析错误,避免代码直接报错:
success: function (data) { try { const responseData = JSON.parse(data.data.response); console.log(responseData.ResStatus); console.log(responseData.ResCode); } catch (e) { console.error('response字段解析失败', e); } },
内容的提问来源于stack exchange,提问作者Hamza Qureshi
相关产品推荐
相关产品推荐

