首页 > 解决方案 > 尝试使用 html 按钮请求 api 调用

问题描述

我正在尝试使用此 html 按钮来调用 api,但无法正常工作。

<button class="col button button-fill" onclick="weather()">Get Weather</button>

<script> unirest.get("https://weatherbit-v1-mashape.p.rapidapi.com/current?
lang=en&lon=<required>&lat=<required>")
.header("X-RapidAPI-Host", "weatherbit-v1-mashape.p.rapidapi.com")
.header("X-RapidAPI-Key","02f2e99835msh60df6f30e23585dp137d84jsn437639993023")
.end(function (result) { console.log(result.status, result.headers, result.body);});</script>

标签: node.jshtml-framework-7

解决方案


您只是在加载脚本时发出请求。没有呼唤它。当按钮被按下时,它引用了一个您没有向我们展示的天气()函数。我假设脚本中的给定代码是单击按钮时要运行的代码。为此,您需要将其放在由 onclick 触发的函数中。所以是这样的:

<script>
function weather(){
    unirest.get("https://weatherbit-v1-mashape.p.rapidapi.com/currentlang=en&lon=<required>&lat=<required>")
    .header("X-RapidAPI-Host", "weatherbit-v1-mashape.p.rapidapi.com")
    .header("X-RapidAPI-Key","02f2e99835msh60df6f30e23585dp137d84jsn437639993023")
    .end(function (result) { console.log(result.status, result.headers, result.body);});
}
</script>

按钮标签中的 onclick 会查找放在引号中的函数,它不会为您创建一个函数。


推荐阅读