【问题标题】:How to Store Fetch API JSON Response in a JavaScript Object如何在 JavaScript 对象中存储 Fetch API JSON 响应
【发布时间】:2019-09-02 17:14:28
【问题描述】:

我想将 Fetch API JSON 存储为 JavaScript 对象,以便在其他地方使用它。 console.log 测试有效,但我无法访问数据。

以下作品:它显示了带有三个待办事项的控制台条目:

 fetch('http://localhost:3000/api/todos')
    .then(data => data.json())
    .then(success => console.log(success));

以下不起作用:

fetch('http://localhost:3000/api/todos')
.then(data => data.json())
.then(success => JSON.parse(success));

如果我尝试访问成功,它不包含任何数据。

试过console.log,效果很好。

还尝试了以下方法,效果很好:

fetch('http://localhost:3000/api/todos')
    .then(res => res.json())
    .then(data => {
        let output = '';
        data.forEach(function (todo) {
        output += `
            <ul>
                <li>ID: ${todo.id}</li>
                <li>Title: ${todo.title}</li>
                <li>IsDone: ${todo.isdone}</li>
            </ul>
            `;
        });
        document.getElementById('ToDoList').innerHTML = output;
        return output;
    })
    .catch(err => console.log('Something went wrong: ', err));

但是,我无法手动更新内部 HTML;我需要该对象来执行其他用户体验。

【问题讨论】:

  • success =&gt; JSON.parse(success) data.json() 解析为 JSON。无需再次解析

标签: javascript json api fetch-api


【解决方案1】:

您可以在外部声明一个变量,然后像这样将结果分配给它

var yourTodos;

fetch('http://localhost:3000/api/todos')
    .then(data => data.json())
    .then(success => yourTodos = success);

然后您将 yourTodos 作为您的 javascript 对象,您可以随意使用它。

【讨论】:

    【解决方案2】:

    你也可以使用如下函数:

     function doSomething(success){
       //do whatever you like
     }
    
     fetch('http://localhost:3000/api/todos')
        .then(data => data.json())
        .then(success => doSomething(success));
    

    【讨论】:

    • 如果对你有帮助。请选择我的答案作为正确答案。提前致谢。
    【解决方案3】:

    你可以像下面这样使用异步等待

    async function consumingFunc () {
      let response = await fetch('http://localhost:3000/api/todos')
      console.log(response)
    }
    
     consumingFunc()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2022-01-21
      • 2022-01-06
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      相关资源
      最近更新 更多