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

使用fetch()传递PHP数组至JS遇TypeError错误,求解决方案

问题解决方案

错误原因分析

你遇到的报错Uncaught (in promise) TypeError: respons.json is not a function主要来自两个问题:

  1. 变量拼写错误:respons应为response
  2. 未正确处理fetch返回的Promise:fetch返回的是Promise对象,必须用await获取实际的Response实例后才能调用.json()方法
  3. PHP输出方式错误:方式1输出的是script标签,不符合fetch对纯JSON响应的要求;方式2缺少正确的响应头设置

修正后的完整代码

PHP文件(pscript.php)

<?php
// 此处省略数据库连接、查询$result的代码
$timeslots = array();
while ($cells = mysqli_fetch_assoc($result))
{
  array_push($timeslots, $cells['rectime']);
}

// 设置响应头,明确告知浏览器返回的是JSON数据
header('Content-Type: application/json');
// 输出纯JSON格式的数组
echo json_encode($timeslots);
exit; // 确保后续无多余输出,避免污染JSON结构
?>

JS文件(script.js)

async function getResponse() {
  try {
    // 修正拼写错误,并用await获取Response对象
    let response = await fetch('pscript.php', {
      method: 'GET',
      headers: { 'Accept': 'application/json' } // GET请求无需Content-Type,用Accept指定期望响应类型
    });

    // 检查请求是否成功
    if (!response.ok) {
      throw new Error(`请求失败,状态码:${response.status}`);
    }

    let content = await response.json();
    console.log(content);
  } catch (error) {
    console.error('请求出错:', error);
  }
};

getResponse();

关键注意事项

  • 确保PHP文件没有任何多余输出(比如开头的空格、HTML标签等),否则会破坏JSON结构导致解析失败
  • GET请求不需要设置Content-Type请求头,因为GET请求没有请求体,设置Accept头告知服务器期望JSON响应更合理
  • 增加try/catch可以捕获请求和解析过程中的错误,便于调试

内容的提问来源于stack exchange,提问作者naffi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:43:26