You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:09:04