【问题标题】:How do I return data from fetch and display in div?如何从获取中返回数据并在 div 中显示?
【发布时间】:2021-10-10 20:16:24
【问题描述】:

例如,这里是远程 URL 上 JSON 的内容:

{ "title": "The title", "description": "The description" }

你能帮忙吗:

  • 我想从远程 url 获取 json 数据(异步任务)。
  • 返回值时,我想在DIV中显示标题(json)。

下面的函数在我的 DIV 中显示“[object Promise]”。

async buildWidget() {
    var id = "whatever"
    let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
    var json = data.json();
    
    return json.title;
}

请不要使用 JQuery。

谢谢

【问题讨论】:

  • json 是一种异步方法。在从中读取字段之前,您还需要 await 它。
  • 1.在data.json() 之前放置一个await 关键字。 2.调用buildWidget函数为:buildWidget().then(title => { /* show title in div */}).catch(err => { /* handle error*/})
  • 我明白了,主要问题是我如何调用该函数。谢谢
  • 如果你调用buildWidget()的上下文也是异步的,那么你可以简单地使用await buildWidget()

标签: javascript async-await fetch


【解决方案1】:

在 .json() 上使用 await,因为它是异步的,即

async buildWidget() {
    var id = "whatever"
    let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
    var json = await data.json();
    
    return json.title;
}

【讨论】:

    【解决方案2】:

    fetch 方法返回一个承诺,所以只需 await 并从中获取 JSON 响应。然后,您可以简单地获取 data.titledata.description 之类的属性,然后渲染到 DOM。

    async function buildWidget() {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
      const data = await response.json();
    
      document.getElementById('data').innerHTML = data.title;
    }
    
    buildWidget();
    <div id="data"></div>

    【讨论】:

      【解决方案3】:

      首先.json()返回一个promise,然后还需要await

      第二:async 函数是异步的,它们返回一个承诺。

      async buildWidget() {
          var id = "whatever"
          let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
          var json = await data.json();
          
          return json.title;
      }
      
      buildWidget().then(title => {
         console.log(title)
      })
      

      【讨论】:

        猜你喜欢
        • 2012-01-19
        • 2012-11-08
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-26
        • 2020-04-21
        • 1970-01-01
        相关资源
        最近更新 更多