fab*_*nod 0 html javascript 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>
Run Code Online (Sandbox Code Playgroud)
如何将 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");
});
}
Run Code Online (Sandbox Code Playgroud)
在这里您可以通过示例查看Body.json()的文档
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |