如何在 HTML 中调用 REST API [英] How to call REST API in HTML
问题描述
API Noob 在这里,我真的很难弄清楚 API 和谷歌教程让我认为它们比我认为的更先进.这是我想要做的:
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:
创建一个简单的网页,让我可以搜索位于此 pokemon API 的信息:https://pokeapi.co/
Create a simple webpage that allows me to search the information located at this 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>
感谢您的帮助!
推荐答案
在这里你需要一些 Javascript.这样的事情应该可以工作:
you'll need some Javascript here. Something like this should work:
<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>
此代码正在使用 fetch 函数(更多信息此处 ) 向 apiUrl 变量中包含的 url 发出 GET 请求.您可能希望使用 HTML 输入标签使 Pokemon 名称动态化.
this code is using the fetch function ( more info here ) to make a GET request to the url contained in the apiUrl variable . You may want to use an HTML input tag to make the Pokemon name dynamic.
这篇关于如何在 HTML 中调用 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!