如何从PHP文件提供的API获取数据,使用result.data拿不到返回值怎么办?
问题原因
你无法读取result.data是两个问题共同导致的:
- 代码中调用了
response.text(),会把接口返回的所有内容解析为纯文本字符串,字符串本身不存在data属性,读取后必然返回undefined - 只有将返回内容解析为JavaScript对象后,才能正常读取对应的嵌套属性
修复方案
方案1(推荐,接口返回JSON格式时使用)
如果你的PHP接口返回的是标准JSON结构,直接把response.text()替换为response.json()即可,修改后代码如下:
var formdata = new FormData(); formdata.append("stock_symbol", "PPL"); var requestOptions = { method: 'POST', body: formdata, redirect: 'follow' }; fetch(url, requestOptions) .then(response => response.json()) // 替换原text()方法为json() .then(result => { console.log('result', result.data) }) .catch(error => console.log('error', error));
方案2(接口返回纯文本时使用)
如果接口确实返回的是纯文本格式的JSON字符串,可以手动调用JSON.parse()转换为对象后再读取属性:
fetch(url, requestOptions) .then(response => response.text()) .then(result => { const resObject = JSON.parse(result) console.log('result', resObject.data) }) .catch(error => console.log('error', error));
额外提示:调试时可以先打印完整的result内容确认返回结构,同时要确保你的PHP接口返回的JSON结构中确实存在data字段,响应头Content-Type设置为application/json,避免出现解析错误
内容的提问来源于stack exchange,提问作者Adeel
相关产品推荐
相关产品推荐

