如何将 Google PageSpeed Insight JSON 结果转换为 HTML

How to convert Google PageSpeed Insight JSON results to HTML

我以前从未使用过 JSON,我一直在将结果转换为 html。我希望他们最好吐出 ul 和 li。我试过插件和 Jquery 脚本,但似乎没有任何效果。我的假设是我吐出结果的方式是不正确的,但正如我所说,我不知道我在用服务器响应对象做什么。

HTML:

<input type="text" placeholder="Enter webpage URL e.g.http://www.domain.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.domain.com</div>
<pre id="data"></pre>

我获取结果的代码:

<script>
function clicked()
{   
    document.getElementById("urlerror").style.display = 'none'; 
    var xhr = new XMLHttpRequest();
    var url = document.getElementById("url").value;
    if(url.indexOf('http://') === -1){document.getElementById("urlerror").style.display = 'block'; return;}
    var xhr =  new XMLHttpRequest();
    xhr.open("GET", "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url="+encodeURIComponent(url)+"&key=AIzaSyAIOUFcLYeo2WN1qbPSjlMbXmLi8kmOacw&strategy=mobile");
    xhr.onload = function(){
    document.getElementById("data").innerHTML = xhr.responseText;
}
xhr.send();
}
</script>

生成的短片段 JSON 对象示例(非完整代码):

{
 "kind": "pagespeedonline#result",
 "id": "http://www.celebritynewsdaily.us/",
 "responseCode": 200,
 "title": "Celebrity News Daily | Your Daily Source for Celebrity News & Updates",
 "score": 64,
 "pageStats": {
  "numberResources": 71,
  "numberHosts": 13,
  "totalRequestBytes": "11777",
  "numberStaticResources": 35,
  "htmlResponseBytes": "235467",
  "textResponseBytes": "238",
  "cssResponseBytes": "135950",
  "imageResponseBytes": "545748",
  "javascriptResponseBytes": "762058",
  "otherResponseBytes": "107518",
  "numberJsResources": 13,
  "numberCssResources": 11
 },
  "formattedResults": {
  "locale": "en_US",
  "ruleResults": {
  "AvoidInterstitials": {
  "localizedRuleName": "Avoid app install interstitials that hide content",
  "ruleImpact": 0.0,
  "urlBlocks": [
  {
  "header": {
  "format": "Your page does not appear to have any app install interstitials that hide a significant amount of content. Learn more about the importance of avoiding the use of app install interstitials.",
  "args": [
    {
     "type": "HYPERLINK",
     "value": "https://developers.google.com/webmasters/mobile-sites/mobile-seo/common-mistakes/avoid-interstitials"
      }
     ]
    }
   }
  ]
 }
}

非常感谢任何帮助实现此工作的帮助。

获得 JSON 字符串后,很容易通过调用 JSON.parse().

将其转换为 JavaScript 对象
var myObject = JSON.parse(jsonString);

获得对象后,您可以像普通 JS 对象一样引用其中的值;例如 myObject.pageStats.numberResources,并使用 DOM 方法将它们插入到 DOM 元素中。