猿问

无法在 Jquery 中保存获取的数据

我正在处理我的前端,我遇到了一个障碍。我正在尝试从后端获取数据,它实际上是在获取数据。但只有在其他一切之后?我会给你看。


$(function(){

    function GetURLId() {

        var url = window.location.href;

        var path = url.substring(url.lastIndexOf('/') + 1);

        var id = path.substring(path.lastIndexOf('?id=') + 4, path.lastIndexOf("?id") + 5)

        return id;

    }



    var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();


        fetch(url)

        .then((resp) => resp.json()) 

        .then(function(data) {

            Object.keys(data).forEach(key => {

                console.log(`${key}: ${data[key]}`);

            })

        });

});

所以首先我从 URL 中得到我正在使用的 id。那么问题出在它下面的代码。我可以在控制台中获取我的数据。记录这个:


id: 2

status: "Open"

damage: true

所以数据实际上是从我的后端获取的。但是现在,每次我尝试保存数据时,它都未定义。我试过了:


$(function(){

    var rental = []; // Added an array

    var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();


        fetch(url)

        .then((resp) => resp.json()) 

        .then(function(data) {

            Object.keys(data).forEach(key => {

                console.log(`${key}: ${data[key]}`);

                rental.push(rental[key] = data[key]);

            })

        });

    console.log(rental['id']); // Returns undefined

});

和:


var rental = []; // Added an array outside of the function

$(function(){

    var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();


        fetch(url)

        .then((resp) => resp.json()) 

        .then(function(data) {

            Object.keys(data).forEach(key => {

                console.log(`${key}: ${data[key]}`);

                rental.push(rental[key] = data[key]);

            })

        });

    console.log(rental['id']); // Returns undefined

});

但!最后一个是在函数之外租用的,我实际上可以在控制台中调用它。在控制台中,它实际上确实返回了值。


Inside Console:

> rental["id"]

< 2


但这也行不通。它在控制台中返回伤害:未定义 3 次。


因此,如果有人知道这里发生了什么,那就太棒了!


慕容708150
浏览 159回答 2
2回答

MYYA

获取请求是异步的。这意味着当您调用fetch它时可能需要一段时间才能完成它,因此 JavaScript 允许其余代码继续执行而不会阻塞。因此,在您的请求完成之前将任何内容记录到控制台显然会导致一个空数组。此外,数组是基于索引的,而不是基于 JavaScript 的名称。但是,由于数组本质上是对象,所以它仍然可以工作,但您永远不应该执行以下操作。var rental = [];rental['id'] = 'foo';console.log(rental['id']);而是使用一个普通的对象,该对象旨在以这种方式使用。var rental = {};rental['id'] = 'foo';console.log(rental['id']);在你的最后一个例子中,你似乎做的一切都很好。您确定您的 fetched在其结构data中没有值吗?undefined这将有助于查看数据的样子。

12345678_0001

答案:我的代码中有 2 个错误。- 首先,我没有正确考虑代码的异步性质。- 其次,当试图用另一个修复它时,然后阻止并在那里执行我的代码。我没有在进程 then 块中返回值,而是返回了 forEach。fetch(url)&nbsp; &nbsp; &nbsp; &nbsp; .then(resp => resp.json())&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; .then(data => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var rentalStatus;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object.keys(data).forEach(key => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rental[key] = data[key];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(key == "status") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rentalStatus = data[key];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return rentalStatus;&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .then(rentalStatus => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(rental["id"]); // This does return the id now!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(rentalStatus == "Reserved") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#assign-items").removeClass("d-none");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }).catch(error => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("Error:" + error);&nbsp; &nbsp; &nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答