javascript - 在 html 中使用 fetch api
问题描述
fetch
关于在 html 文件中的使用,我有一个简单的问题。
我在 AWS Api Gateway 中创建了一个 API,它有一个简单的 GET 方法:GET 方法返回一个 json。
现在,如果我直接访问或使用邮递员访问我的方法的链接,它可以正常工作,但是当我尝试使用fetch
错误时,会发生错误并且我看不到任何结果。
我在互联网上搜索,因为我既不知道 javascript 也不知道 html,但我找不到如何使它正常工作。例如,我在下面的代码中尝试做的是将通过 GET 获取的 json 放入标签中。
这是我的 html 文件:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>test.html</title>
</head>
<body>
<dl>
<dt>Page 1</dt>
<dd>Go to <a href="https://xxx.execute-api.eu-central-
1.amazonaws.com/prod/getcustomerdetailsbyemail/">link</a></dd>
</dl>
<p> <input name="Button" value="Click me" onclick="buttonClick()" type="button"> <input
name="Button2" value="Click me 2" formmethod="get" onclick="buttonClick2()" type="button">
</p>
<p> <input id="myText" name="Message" value="Insert text" type="text"></p>
<label for="myText" id="mylabel"></label>
<div id="myData"> </div>
<dl>
</dl>
<dl>
</dl>
<script type="text/javascript">
function buttonClick(){
alert(document.getElementById("myText").value);
}
</script>
<script type="text/javascript">
function buttonClick2(){
fetch("https://xxx.execute-api.eu-central-1.amazonaws.com/prod/getcustomerdetailsbyemail")
.then(response => {
document.getElementById("mylabel").value = response.json();
})
.catch(error => {
alert("Nope");
});
</script>
</body>
</html>
如何将 get 调用返回的 json 放入标签中?
我还有一个问题:如果我 console.log("message")
在 html 文件中放入一个脚本,那么当脚本运行时我会发生什么?(剧透:什么都没发生,为什么?)
如果我忽略了一些重要的事情,我很抱歉,但我不知道从哪里开始。
解决方案
问题是response.json()
产生一个Promise,所以你需要等待它解决并使用结果:
function buttonClick2(){
fetch("https://your-url.com")
.then(response => response.json()) // <-- important line
.then(response => {
// changed .value to .innerHTML but you can handle it as you wish
document.getElementById("mylabel").innerHTML = response;
})
.catch(error => {
alert("Nope");
});
}
在这里您可以通过示例查看Body.json()的文档
推荐阅读
- wordpress - 如何在我的 wordpress 主题中制作预订表格
- javascript - 套接字挂断后nodejs api不起作用并自动解决
- mysql - 仅允许一行用于特定值,但不允许其他值
- javascript - 有没有办法从 URL 导入脚本包?
- c# - 重复事件未在通知中返回实际 ID
- c# - 错误请求错误 400:使用 mime 请求使用 web 服务
- javascript - 如何将自定义 js 文件添加到公开的 reactjs
- reactjs - React-Native FlatList 滚动方向
- git - SSH 无法正常工作,导致 ssh 错误致命:协议错误:错误的行长度字符:git@
- authorization - 为什么 Envoy ext-authz 不遵守 connect_timeout?