如何在HTML中打印出json ?



我想从链接中打印出html中的数据,但它总是显示"undefined"我不知道问题出在哪里。有人能帮忙吗?

let url = 'https://ac7minh6n7s3rw4qfchrofbwai0amiko.lambda-url.eu-north-1.on.aws/';
fetch(url)
.then(res => res.json())
.then(out => console.log('JSON: ', out))
.then(out => document.write('JSON string: ', JSON.stringify(out)))
.catch(err => { throw err })

传递给then回调的值是链中前一个链接的返回值。如果该值是一个promise,则在调用then之前解析它。

.then(out => console.log('JSON: ', out))

console.log的返回值是undefined,所以你将undefined传递给试图document.write值的函数。

你需要返回你想要处理的值:

.then(out => {
console.log('JSON: ', out);
return out;
})

然而因为你没有创建一个新的承诺,真的没有必要使用额外的then。你可以合并这两个:

.then(out => {
console.log('JSON: ', out);
document.write('JSON string: ', JSON.stringify(out);
return out;
})

之所以是undefined,是因为console.log()的返回值是undefined。删除它允许out被引用:

let url = 'https://ac7minh6n7s3rw4qfchrofbwai0amiko.lambda-url.eu-north-1.on.aws/';
fetch(url)
.then(res => res.json())
.then(out => document.write('JSON string: ', JSON.stringify(out)))
.catch(err => { throw err });

最新更新