如何从 API 获取 JSON 文件中的某个数据片段?

我对 API 和脚本很陌生。我想知道如何在我的网站上打印一段数据,例如:

我想在下次启动时只打印“名称”标签

https://launchlibrary.net/1.4/launch/next/1


慕婉清6462132
浏览 107回答 2
2回答

波斯汪

您可以在获取数据后尝试使用函数。您可以使用 或 方法 从下面的 api 示例中获取数据。mapfetchjquery ajax映射返回到新数组,如果你只需要取第一个元素,那么你可以说data.launches.map(x=>x.name )[0]&nbsp;$(document).ready(function(){&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'GET',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "https://launchlibrary.net/1.4/launch/next/1",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success:function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(data.launches.map(x=>x.name ));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>使用纯 jsfetch('https://launchlibrary.net/1.4/launch/next/1')&nbsp; &nbsp; .then(r => r.json())&nbsp; &nbsp; .then(data => console.log(data.launches.map(x=>x.name)));

慕沐林林

如果该 API 设置了适当的 CORS 标头(从我的测试来看似乎确实如此),则可以使用名为 fetch 的本机浏览器函数调用它。例如:fetch('https://launchlibrary.net/1.4/launch/next/1')&nbsp; &nbsp; // Convert response to JSON&nbsp; &nbsp; .then(r => r.json())&nbsp; &nbsp; // Show name in console&nbsp; &nbsp; .then(data => console.log(data.launches[0].name));然后,您可以使用数据与 DOM 进行交互,如下所示:fetch('https://launchlibrary.net/1.4/launch/next/1')&nbsp; &nbsp; // Convert response to JSON&nbsp; &nbsp; .then(r => r.json())&nbsp; &nbsp; // Show name to user&nbsp; &nbsp; .then(launchData => alert(launchData.launches[0].name));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript