2015-09-16 52 views
1

我从来没有使用过JSON,而且我坚持将结果转换为html。我希望他们最好吐出ul和li。我尝试过插件和Jquery脚本,但似乎没有任何工作。我的假设是,我吐出结果的方式是不正确的,但正如我所说,我不知道我在做什么与服务器响应对象。如何将Google PageSpeed Insight JSON结果转换为HTML

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" 
     } 
    ] 
    } 
    } 
    ] 
} 
} 

任何帮助越来越这项工作非常感谢。

回答

2

一旦获得了JSON字符串,就可以通过调用JSON.parse()轻松转换成JavaScript对象。

var myObject = JSON.parse(jsonString); 

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

+0

这是我想念的一步,非常感谢你。 –

+0

你能从OP的代码中向我们展示你可以输入'var myObject'的位置吗? – PhpDude