我如何 return 获取数据并显示在 div 中?

How do I return data from fetch and display in div?

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

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

你能帮忙解决一下吗:

下面的函数在我的 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,因为它是异步的,即

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

首先.json()return作为一个承诺然后还需要await为之

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

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)
})

fetch 方法 returns 一个承诺,所以只需 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>