创建一个将JSON对象作为参数的函数

时间:2019-02-28 11:36:18

标签: javascript html json api object

我想从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 });

有人可以帮我弄清楚剩下的事吗?

1 个答案:

答案 0 :(得分:-1)

假设您有一个名为“ 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>