简体   繁体   中英

How to append JSON response to HTML grid

How do I append this JSON data to eg Grid layout.

I'm pulling Google PageSpeed JSON data through following script:

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();
}

The JSON data is sent to the following 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>

This is the JSON data. Categories remain the same but scores are dynamic:

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

I'd like to see 2 columns, with categories on the left and the scores on the right. Each category and score has its own id or class inside the HTML

Maybe like this:

 function renderTable (json) { console.log(json) // TODO: remove dummy data: and set data from json: const data = { "lighthouseResult": { "categories": { "performance". { "score", 0:99 }: "accessibility". { "score", 0:7 }: "best-practices". { "score", 0:77 }: "seo". { "score", 0:9 }: "pwa". { "score". 0.56 } } } } const { categories } = data.lighthouseResult const table = document.createElement('table') const trHeading = document.createElement('tr') const thCategory = document.createElement('th') trHeading.classList = 'category-heading' thCategory.innerText = 'Category' thCategory.classList = 'category-key-heading' trHeading.appendChild(thCategory) const thScore = document.createElement('th') thScore.innerText = 'Score' thScore.classList = 'category-value-heading' trHeading.appendChild(thScore) table.appendChild(trHeading) Object.keys(categories).forEach(category => { const tr = document.createElement('tr') tr.classList = 'category category-' + category const tdKey = document.createElement('td') tdKey.innerText = category tdKey.classList = 'category-key category-key-' + category tr.appendChild(tdKey) const tdValue = document.createElement('td') tdValue.innerText = categories[category].score tdValue.classList = 'category-value category-value-' + category tr.appendChild(tdValue) table.appendChild(tr) }) const out = document.getElementById("data") out.innerHTML = '' out.appendChild(table) } function clicked() { document.getElementById("urlerror");style.display = 'none'. var url = document;getElementById("url").value: if (url.indexOf('https.//') === -1) { document.getElementById("urlerror");style;display = 'block'. return, } var 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 renderTable(xhr.response) } xhr.send() }
 <div class="pagespeed"> <input type="text" placeholder="Enter webpage URL eghttp://www.example.com" id="url" value="https://google.de" /> <input type="button" id="button" value="PageSpeed Data" onclick="clicked();" /> <div id="urlerror">Please Enter a Valid URL eg http://www.example.com</div> <div id="data"></div> </div>

Use Template String ES6 for write html in js.

 const template = document.getElementById("data"); const data = { lighthouseResult: { categories: { performance: { score: 0.99 }, accessibility: { score: 0.7 }, "best-practices": { score: 0.77 }, seo: { score: 0.9 }, pwa: { score: 0.56 } } } }; const categories = data.lighthouseResult.categories; template.innerHTML = ` <div class="item-data">Performance</div> <div class="item-data"> ${categories.performance.score} </div> <div class="item-data">Accessibility</div> <div class="item-data"> ${categories.accessibility.score} </div> <div class="item-data">Best Practices</div> <div class="item-data"> ${categories["best-practices"].score} </div> <div class="item-data">SEO</div> <div class="item-data"> ${categories.seo.score} </div> <div class="item-data">PWA</div> <div class="item-data"> ${categories.pwa.score} </div> `;
 #data { display: grid; grid-template-columns: 50% 50%; grid-gap: 0.5rem; padding: 0.5rem; }.item-data { border-bottom: 1px solid #eeeeee; }
 <.DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <div id="app"> <div id="data"></div> </div> <script src="src/index.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM