使用fetch()传递PHP数组至JS遇TypeError错误,求解决方案
问题解决方案
错误原因分析
你遇到的报错Uncaught (in promise) TypeError: respons.json is not a function主要来自两个问题:
- 变量拼写错误:
respons应为response - 未正确处理fetch返回的Promise:fetch返回的是Promise对象,必须用
await获取实际的Response实例后才能调用.json()方法 - 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
相关产品推荐
相关产品推荐

