如何将JSON响应附加到HTML网格

问题描述 投票:1回答:2

我如何将此JSON数据附加到Grid布局。

我正在通过以下脚本提取Google PageSpeed JSON数据:

function clicked () {
  const url = document.getElementById('url').value;

  document.getElementById('urlerror').style.display = 'none';

  if (url.indexOf('https://') === -1) {
    document.getElementById('urlerror').style.display = 'block';
    return;
  }

  const xhr = new XMLHttpRequest();

  xhr.open('GET', `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(url)}&fields=lighthouseResult%2Fcategories%2F*%2Fscore&prettyPrint=false&strategy=desktop&category=performance&category=pwa&category=best-practices&category=accessibility&category=seo&key={YOUR_API_KEY}`);

  xhr.onload = function () {
    document.getElementById('data').innerHTML = xhr.responseText;
  }

  xhr.send();
}

JSON数据发送到以下div

<div class="pagespeed">
    <input type="text" placeholder="Enter webpage URL e.g.http://www.example.com" id="url" />
    <input type="button" id="button" value="PageSpeed Data" onclick="clicked();" />
    <div id="urlerror">Please Enter a Valid URL e.g. http://www.example.com</div>
    <pre id="data"></pre>
</div>

这是JSON数据。类别保持不变,但分数是动态的:

{
  "lighthouseResult": {
    "categories": {
      "performance": {
        "score": 0.99
      },
      "accessibility": {
        "score": 0.7
      },
      "best-practices": {
        "score": 0.77
      },
      "seo": {
        "score": 0.9
      },
      "pwa": {
        "score": 0.56
      }
    }
  }
}

我想看到2列,左边是类别,右边是得分。每个类别和得分在HTML内都有自己的ID或类]

如何将这个JSON数据附加到网格布局。我通过以下脚本提取Google PageSpeed JSON数据:function clicked(){const url = document.getElementById('url')。value; ...

javascript json pagespeed
2个回答
0
投票

也许像这样:


0
投票

使用模板字符串ES6在js中编写html。

© www.soinside.com 2019 - 2024. All rights reserved.