簡體   English   中英

如何解析 fetch JSON 返回並將元素放入 HTML 頁面?

[英]How can I parse fetch JSON return and put elements in to HTML page?

使用 Javascript 獲取 api 我有一個 HTML 頁面如下:

<body>

<div> <button onclick="github();">Get</button> </div>

<div id ="resp">    </div>
</body>

和 Javascript function 如下:

<script type="text/javascript">
  function github() {
  fetch('https://api.github.com/users/KrunalLathiya')
  .then(response => response.json())
  .then(data => {
    console.log(JSON.stringify(data)) // Prints result from `response.json()` in getRequest
    const obj = JSON.stringify(data)
    document.getElementById("resp").innerHTML = obj["html_url"]
    })
  .catch(error => console.error(error))
   }
  </script>

返回的 json 在控制台中打印正常,但在 resp div 中顯示為“未定義”,或者嘗試使用不同的方法對象 [對象]

如何循環遍歷 json 返回並打印 html 頁面上的元素? 然后,通過擴展,使用 Python Flask 應用程序? 謝謝!

您錯誤地將返回的數據字符串化,然后將該(字符串)視為 object。這是一個打印返回數據的所有鍵和值的簡單通用代碼段。

 github(); function github() { const responseContainer = document.querySelector("#resp"); fetch('https://api.github.com/users/KrunalLathiya').then(response => response.json()).then(data => { Object.entries(data).forEach( ([key, value]) => responseContainer.textContent += `${key}: ${value}\n` ) }).catch(error => console.error(error)) }
 <pre id="resp"></pre>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM