最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to stop "[object Object]" from printing rather than the object itself? - Stack Overflow

programmeradmin5浏览0评论

my problem probably has an incredibly easy fix, but I'm new to javascript and can't seem to find an answer for it. Heres the script:

var proxyUrl = '/',
    targetUrl = '/[key]/[latitude],[longitude]'
fetch(proxyUrl + targetUrl)
  .then(blob => blob.json())
  .then(data => {
    console.log(data);
    document.getElementById('weather').innerHTML = data;
  })

However when i run it, the <p> element doesnt change to the data itslef, it changes to "[object Object]" What am I doing wrong? Any help is appreciated.

PS: the targetUrl variable has placeholders where the parameters go, it won't run as-is.

my problem probably has an incredibly easy fix, but I'm new to javascript and can't seem to find an answer for it. Heres the script:

var proxyUrl = 'https://cors-anywhere.herokuapp./',
    targetUrl = 'https://api.darksky/forecast/[key]/[latitude],[longitude]'
fetch(proxyUrl + targetUrl)
  .then(blob => blob.json())
  .then(data => {
    console.log(data);
    document.getElementById('weather').innerHTML = data;
  })

However when i run it, the <p> element doesnt change to the data itslef, it changes to "[object Object]" What am I doing wrong? Any help is appreciated.

PS: the targetUrl variable has placeholders where the parameters go, it won't run as-is.

Share Improve this question edited Aug 18, 2019 at 19:36 Wyatt Nulton asked Aug 18, 2019 at 19:34 Wyatt NultonWyatt Nulton 1591 gold badge3 silver badges11 bronze badges 4
  • data is not a string, it is an object. Your console.log(data) will show you the contents of the object. If there's a specific property of the object you want to display, use data.PropertyName. – Tyler Roper Commented Aug 18, 2019 at 19:35
  • If you want to print the whole object just use: JSON.stringify(data); – Adrian Commented Aug 18, 2019 at 19:35
  • Is "weather" I'd of the <p> element? – Sangwin Gawande Commented Aug 18, 2019 at 19:37
  • Setting the innerHTML value will call toObject which will print [object Object] – evolutionxbox Commented Aug 18, 2019 at 19:37
Add a ment  | 

2 Answers 2

Reset to default 6

From what I understand you are trying to print the data into <p> element with id as "weather".

Please replace following line.

document.getElementById('weather').innerHTML = JSON.stringify(data);

It will work just fine.

Check the data returned by the API call and then add it to the html. I think it is returning an object and you are trying to display that object in the DOM.

发布评论

评论列表(0)

  1. 暂无评论