node.js - 尝试使用 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>
解决方案
您只是在加载脚本时发出请求。没有呼唤它。当按钮被按下时,它引用了一个您没有向我们展示的天气()函数。我假设脚本中的给定代码是单击按钮时要运行的代码。为此,您需要将其放在由 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 会查找放在引号中的函数,它不会为您创建一个函数。
推荐阅读
- android - 为什么即使我在 xml 中有按钮 ID,它仍然会显示“未解析的引用:按钮”?
- apexcharts - 如何让 APEXChart 从 JSON AJAX 响应中呈现
- windows - GitLab Runner 未启动进程
- flutter - 无法从动画列表中删除项目'getter 'currentState' 在 null 上被调用。接收者:null 尝试调用:currentState'
- javascript - React Native NavigationContainer 不显示任何内容
- html - 在某些分辨率下,嵌入式 div 中出现不需要的空白 [chrome]
- json - 将 json 提交到休息端点时出现错误
- go - 如何避免在失败情况下重复返回 InternalServerError?
- javascript - 使用 JavaScript 或 jQuery 将字符串转换为 HTML 元素
- javascript - 将函数的结果存储在本地存储中