首页 > 解决方案 > 创建一个将 JSON 对象作为参数的函数

问题描述

我想从 API 中检索信息,然后创建一个将 JSOn 对象作为参数的函数。然后从返回 JSON 数据的方法中调用函数并传入 JSON 数据。到目前为止,我已经使用 fetch() 链接到 API:

let url = "https://api.magicthegathering.io/v1/cards";

fetch(url)
.then(res => res.json())
.then((out) => {
  console.log("JSON", out);`enter code here`
})
.catch(err => { throw err });

有人可以帮我弄清楚其余的怎么做吗?

标签: javascripthtmljsonapiobject

解决方案


假设你有一个名为“handle_data”的函数,你可以这样称呼它:

<html>
<head>
	<script>

		function handle_data(data) {
			console.log('Data below was printed by handle_data function')
			console.log(JSON.stringify(data))
		}

		function get_json(){
			fetch('https://api.github.com/orgs/nodejs')
			.then(response => response.json())
			.then(data => {
				handle_data(data)
			})
			.catch(error => console.error(error))
		
		}
	</script>
<head>

<body>
	<button type="button" onclick="get_json();">Demo</button>
</body>
</html>


推荐阅读