【问题标题】:Creating a function that takes JSON object as an argument创建一个将 JSON 对象作为参数的函数
【发布时间】:2019-07-22 07:35:54
【问题描述】:

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

有人可以帮我弄清楚剩下的事情怎么做吗?

【问题讨论】:

  • 如何创建函数和处理参数是你应该从介绍性 JavaScript 教程中学习的东西,而不是 Stackoverflow 问题。

标签: javascript html json api object


【解决方案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>

【讨论】:

  • 这行不通。 res 在第二个 then 处理程序的范围内未定义。尝试使用它会引发异常。
  • 代码经过修改和测试。
  • 感谢您的帮助!不过,我不应该在我的 HTML 中使用按钮。我想检索我制作的 JSON 文件中的信息并从中制作卡片。除非我使用我之前发送的那个,否则 fetch() 也不起作用。但我会在我的代码中尝试一下,看看它做了什么! :)
  • 按钮只是一个触发获取代码的触发器。代码的本质是展示如何将我们使用 fetch 获得的数据发送到其他函数 (handle_data) 以使用它做一些有用的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
相关资源
最近更新 更多