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

时间:2015-09-16 20:42:41

标签: javascript jquery html json google-pagespeed

我之前从未使用过JSON,但我仍然坚持将结果转换为html。我希望他们最好是吐出来的。我已经尝试了插件和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"
      }
     ]
    }
   }
  ]
 }
}

非常感谢任何有助于此工作的帮助。

1 个答案:

答案 0 :(得分:2)

获得JSON字符串后,可以通过调用JSON.parse()轻松转换为JavaScript对象。

var myObject = JSON.parse(jsonString);

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