【发布时间】:2021-11-07 07:25:12
【问题描述】:
<!DOCTYPE html>
<head>
<title>home</title>
</head>
<body>
<h1>login here</h1>
<form id="createuserform" method="post">
<label>First Name: </label>
<input id="fname" type="test"></br>
<label>Last Name: </label>
<input id="lname" type="text"></br>
<label>Location: </label>
<input id="location" type="text"></br>
<input id="createUser" type="button" value="create user"></br>
<input id="setter" type="text" value="val">
</form>
<script>
function submitValue() {
var r;
fetch('http://localhost:8080/multimediaApi/api/multimedia/users').then(response => (response.json())).then(data => r = data[0]);
document.getElementById("setter").value = r;
}
</script>
<button onclick="submitValue()">Get Data</button>
</body>
</html>
我想从上面的 API URL 中获取数据并将其存储在变量 r 中。所以,我使用了then(data => r= data[0]) 为变量r 赋值。然后显示在textfielddocument.getElementById("setter").value=r。但是 r 中的值是undefined。
【问题讨论】:
-
您好,为了确定一下,您能否在通话中添加
.catch(e => console.log(e))以确保获取请求不会出错?还要尝试记录您返回的响应,以确保它不是未定义的,并且它具有正确的形状供您使用data[0]访问它。
标签: javascript fetch-api