axios.get获取JSON数据读取字段返回undefined如何解决
问题描述
使用axios.get方法请求后端接口获取模板数据,接口已成功返回JSON格式数据,返回结构如下:
返回数据格式校验正常,数组[]与对象{}嵌套匹配无误,整个结果仅包含1条模板数据,需要读取其中OrederReferencePreffix、InvoiceNumberPreffix等指定字段值,但所有读取尝试均返回undefined,已尝试的读取写法如下:
var attempt_one= json_only[0].InvoiceNumberPreffix; //undefined var attempt_two= response.data.InvoiceNumberPreffix; //undefined var attempt_three= response.data[0].InvoiceNumberPreffix; //undefined var attempt_four= json_only.InvoiceNumberPreffix; //undefined
附相关代码
前端Axios请求代码
axios.get('http://localhost/backend/get_templete.php', { params: { clciked_cpy: cpy } }) .then(function(response) { // 上述字段读取代码均写在此回调内 var json_only = pre_cpy_cut.exec(response.data.toString()); console.log("=]" + json_only); }
后端PHP接口代码
$json = array(); while($row = mysqli_fetch_assoc($result)) { $json[] = $row; } mysqli_free_result($result); echo json_encode( $json, JSON_UNESCAPED_SLASHES ); //返回数据结构与上述截图一致
问题原因
读取失败核心是两个错误操作:
- 多余的正则处理:用正则
exec方法处理response.data.toString()得到的json_only是正则匹配返回的结果数组,不是接口返回的业务数据本身,自然读不到目标字段。 - 数据类型错误:手动将响应数据转为字符串处理,导致拿到的内容是JSON格式的文本,而非Axios默认自动解析完成的JS数组/对象,无法直接通过属性访问语法取值。
正确实现方式
- 先确认后端接口响应头正确,在PHP输出JSON前加上响应头声明,避免Axios无法自动识别解析JSON:
// 加在echo json_encode之前 header('Content-Type: application/json; charset=utf-8');
- 前端删除多余的正则切割、转字符串操作,直接读取Axios自动解析好的响应数据即可:
axios.get('http://localhost/backend/get_templete.php', { params: { clciked_cpy: cpy } }) .then(function(response) { // 后端返回的是包裹单条数据的索引数组,直接取下标0的对象属性即可 const templateData = response.data[0]; const invoicePrefix = templateData.InvoiceNumberPreffix; const orderPrefix = templateData.OrederReferencePreffix; console.log('发票前缀:', invoicePrefix, '订单前缀:', orderPrefix); })
- 如果遇到特殊场景Axios未自动解析JSON,手动执行一次JSON转换再取值即可:
.then(function(response) { const resData = typeof response.data === 'string' ? JSON.parse(response.data) : response.data; const templateData = resData[0]; const invoicePrefix = templateData.InvoiceNumberPreffix; })
内容的提问来源于stack exchange,提问作者Noizy Z
相关产品推荐
相关产品推荐

