使用fetch调用API获取数据无法渲染到表格且控制台无报错如何解决
问题分析与修复方案
存在的问题
- 数据访问层级错误:接口返回的完整数据是外层对象,比赛列表存储在该对象的
data属性中,你当前直接遍历外层对象,而外层对象不是数组,data.length为undefined,循环条件不触发,所以无内容渲染,也不会抛出报错。 - fetch请求参数异常:你配置了POST请求,但是请求体
body: data中的data变量未定义,若接口不需要传参,优先使用GET请求即可。 - 函数声明时序问题:你用
const声明mostrarData函数,不存在变量提升,fetch回调调用函数时函数还未完成定义。
修复代码
修改script部分的代码即可:
// 先声明函数,避免时序问题 const mostrarData = (response) => { console.log(response) let body = '' // 访问response下的data数组进行遍历 const competitionList = response.data for (let i = 0; i < competitionList.length; i++){ body += `<tr><td>${competitionList[i].CompCode}</td><td>${competitionList[i].Name}</td><td>${competitionList[i].Place}</td></tr>` } document.getElementById('data').innerHTML = body } let url = 'http://localhost/api/json/Competitions.php'; // 无参数请求直接用GET,不需要传body fetch(url) .then(response => response.json()) .then(data => mostrarData(data)) .catch(error => console.log(error))
如果接口确实需要POST请求传参,需要先定义要提交的参数变量,同时加上对应的请求头:
// POST传参示例 const postData = {请求参数key: 对应参数值} fetch(url,{ method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postData) })
内容的提问来源于stack exchange,提问作者Club Asirio Huelva
相关产品推荐
相关产品推荐

