javascript 如何在 HTML 中调用 REST API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54600060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call REST API in HTML
提问by Bunny
API Noob here, I'm having a really hard time figuring out API's and google tutorials are leaving me think they are way more advanced then I figure they should be. Here is what I'm trying to do:
API Noob 在这里,我真的很难弄清楚 API 和谷歌教程让我认为它们比我认为的更先进。这是我想要做的:
Create a simple webpage that allows me to search the information located at this pokemon API: https://pokeapi.co/
创建一个简单的网页,让我可以搜索位于此 pokemon API 的信息:https: //pokeapi.co/
Can anyone help me figure out how to write a function to make it work?
谁能帮我弄清楚如何编写一个函数来使其工作?
<!DOCTYPE html>
<html>
<body>
<h1>PokeMon Search API</h1>
<script>//javascript function here?</script>
<input id="text" type="text" value="" style="Width:20%"/>
<button>Find PokeMon By Name</button>
<p>Results</p>
<div v-html="link.FUNCTIONVARIABLE"></div>
</body>
</html>
Thanks for any help!
谢谢你的帮助!
回答by MizRaeL
you'll need some Javascript here. Something like this should work:
你在这里需要一些Javascript。这样的事情应该工作:
<script type="text/javascript">
var apiUrl = 'https://pokeapi.co/api/v2/pokemon/ditto/';
fetch(apiUrl).then(response => {
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
});
</script>
this code is using the fetch function ( more info here) to make a GET request to the url contained in the apiUrlvariable . You may want to use an HTML input tag to make the Pokemon name dynamic.
这段代码使用 fetch 函数(这里有更多信息)向包含在apiUrl变量中的 url 发出 GET 请求。您可能希望使用 HTML 输入标记使 Pokemon 名称动态化。

