无法将获取数据的value属性赋值给innerHTML的问题求助
问题解决:fetch链中数据未传递导致的undefined错误
你的核心问题在于Promise链的数据传递逻辑:
console.log(data.value)这个调用的返回值是undefined,所以下一个.then()回调接收的参数data就是undefined,自然会抛出"Cannot read properties of undefined (reading 'value')"的错误。- 而你之前能打印出
data.value,说明前一步的接口数据是正常获取到的,只是后续的数据传递断了。
这里提供两种修复方案:
方案1:合并两个.then()回调(推荐)
把打印和DOM赋值放在同一个回调里,避免数据传递问题:
<html> <body> <h2>fetch & innerHTML test</h2> <div id='sensorValue'></div> <script> fetch("https://example.com/filename.php?apikey=1567477555629&setting1=1" ) .then( response => { if( ! response.ok ) { throw new Error("Could not fetch resource") } return response.json() }) .then( data => { console.log(data.value); // 先打印数据 document.getElementById('sensorValue').innerHTML = data.value; // 再赋值到DOM }) .catch( error => console.error(error)); </script> </body> </html>
方案2:手动传递数据到下一个.then()
如果需要分开处理逻辑,要在第一个.then()里返回data,确保后续回调能拿到数据:
<html> <body> <h2>fetch & innerHTML test</h2> <div id='sensorValue'></div> <script> fetch("https://example.com/filename.php?apikey=1567477555629&setting1=1" ) .then( response => { if( ! response.ok ) { throw new Error("Could not fetch resource") } return response.json() }) .then( data => { console.log(data.value); return data; // 将数据传递给下一个then回调 }) .then(data => { document.getElementById('sensorValue').innerHTML = data.value; }) .catch( error => console.error(error)); </script> </body> </html>
补充说明:你测试赋值字符串"Test"能成功,说明目标DOM元素#sensorValue是存在的,无需担心元素查找问题,只需要修复Promise链的数据传递即可。
内容的提问来源于stack exchange,提问作者Randy32
相关产品推荐
相关产品推荐

