Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
How do I return data from fetch and display in div?

For example here is the content of a JSON on a remote URL:

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

Could you please help with this:

  • I want to fetch json data from remote url (async task).
  • When the value is returned, I want to display the title (json) in a DIV.

The function below displays "[object Promise]" in my DIV.

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

No JQuery please.

Thanks

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use await on .json() as it is asynchronous I.e.

async buildWidget() {
    var id = "whatever"
    let data = await fetch('getItem.php?id=' + id + '&callback=getJSONP');
    var json = await data.json();
    
    return json.title;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

First of all .json() returns an promise and then also needs to await for it.

Second: async functions are asynchronouse they return an promise.

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)
})
about 4 years ago · Juan Pablo Isaza Relatório

0

fetch method returns a promise, so just await and get the JSON response from it. You can then simply get the properties like data.title or data.description and render then to the 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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda