簡體   English   中英

在 html 頁面上顯示 api 響應

[英]displaying api response on html page

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>JSON Test</title>
</head>
<body>
   <h1>Hello World</h1>
   <div id="myData"></div>
   <script>
       fetch('http://localhost:3000/api/product/1234567')
           .then(function (response) {
               return response.json();
           })
           .then(function (data) {
               appendData(data);
           })
           .catch(function (err) {
               console.log('error: ' + err);
           });
       function appendData(data) {
           console.log(data)
           var mainContainer = document.getElementById("myData");
           for (let key in data) {
               var div = document.createElement("div");
               div.innerHTML = 'name: ' + data[key] + 'label' + data[key];
               mainContainer.appendChild(div);
           }
       }
   </script>
</body>
</html>

嘗試獲取 json 響應並將其顯示在 html 頁面上。 它給了我一個錯誤:SyntaxError: Unexpected end of JSON input。 我想我在這里可能會獲得一些關於如何解決這個問題以及為什么會發生這種情況的幫助。 謝謝你。

編輯:

我在控制台上得到的響應:

{ 產品:1234567,名稱:'TV',salePrice:149.99 }

主要原因是您的響應不是 JSON 格式,這可能是因為獲得了一些非 json 格式的響應。 請發布示例 JSON 響應格式以更好地理解。

暫無
暫無

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

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