【问题标题】:undefined variable comming in fetch api javascript while storing its value in a variable [duplicate]未定义的变量在 fetch api javascript 中出现,同时将其值存储在变量中[重复]
【发布时间】: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 =&gt; r= data[0]) 为变量r 赋值。然后显示在textfielddocument.getElementById("setter").value=r。但是 r 中的值是undefined

【问题讨论】:

  • 您好,为了确定一下,您能否在通话中添加.catch(e =&gt; console.log(e)) 以确保获取请求不会出错?还要尝试记录您返回的响应,以确保它不是未定义的,并且它具有正确的形状供您使用 data[0] 访问它。

标签: javascript fetch-api


【解决方案1】:

submitValue函数的执行过程中,r的值为undefined并发起了一个AJAX请求,该请求将在稍后完成,并将该值分配给

document.getElementById( "setter" ).value = r;

将是 undefined,这是 r 的当前值。


Later some time the request is completed

所以,下面的代码运行

fetch( 'http://localhost:8080/multimediaApi/api/multimedia/users' )
    .then( response => ( response.json() ) )  // now run
    .then( data => r = data[0] );             // now run

在这里,您只是将data[0] 分配给r。其余代码之前已经运行过,不会再次运行。这就是 ASYNC JS 的工作原理。

你应该阅读Understanding JavaScript promise object

您可以直接将data[0]分配给id为setter的HTML元素:

function submitValue() {
    fetch( 'http://localhost:8080/multimediaApi/api/multimedia/users' )
        .then( response => ( response.json() ) )
        .then(data => {
            document.getElementById( "setter" ).value = data[0];
        })
}

【讨论】:

  • 假设我想将 data[0] 的值存储在一个变量中,然后稍后将其用于该场景 .then(data => { document.getElementById( "setter" ).value = data [0]; }) 这段代码没有用。
  • 对于这种情况,您必须将状态提升到最近的公共父级,您可以在其中声明变量并在.then中设置变量的值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2021-06-22
  • 2016-06-18
  • 2016-12-26
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
相关资源
最近更新 更多