2017-09-27 83 views
0

我使用Google pagespeed API来测试我网站的网址。只要url结构不包含任何“&”(查询字符串参数),它就可以正常工作。包含“&”的网址不适用于google pagespeed api

实例(工程)

  1. http://www.example.com
  2. http://www.example.com/?id=1234

但是,当我改变URL这样的事情,那么它并没有显示正确的结果

不起作用的示例

1)http://www.example.com/?id=1234&sub=890

阿比忽略 “&分= 890” 的一部分,并返回http://www.example.com/?id=1234

在API JavaScript代码寻找结果:

function runPagespeed() {   
     var s = document.createElement('script'); 
     s.type = 'text/javascript'; 
     s.async = true; 
     var query = [ 
      'url=' + URL_TO_GET_RESULTS_FOR, 
      'strategy=' + strategy, 
      'callback=runPagespeedCallbacks', 
      'key=' + API_KEY, 
     ].join('&'); 
     s.src = API_URL + query; 
     document.head.insertBefore(s, null); 
    } 

所以看着这个函数显示API将把“sub = 890”作为自己的参数,所以它会忽略它。

当我使用url http://www.example.com/?id=1234&sub=890https://developers.google.com/speed/pagespeed/insights/,它工作正常,并显示结果

注:我使用的PageSpeed示例代码进行测试是https://developers.google.com/speed/docs/insights/v2/first-app

任何帮助将高度赞赏

+0

也许'。加入( '& ')' –

+0

。加入(' &')不工作:( – RashFlash

+0

好,'子= 890'应该不需要任何编码,但在你的代码你有一个完整的URL作为查询字符串,并且在尝试发送它之前确实需要URL编码。 – adeneo

回答

2

您需要使用encodeURIComponent对URI进行编码,以便将参数视为输入。试试下面的

function runPagespeed() {   
     var s = document.createElement('script'); 
     s.type = 'text/javascript'; 
     s.async = true; 
     var query = [ 
      'url=' + encodeURIComponent(URL_TO_GET_RESULTS_FOR), 
      'strategy=' + strategy, 
      'callback=runPagespeedCallbacks', 
      'key=' + API_KEY, 
     ].join('&'); 
     s.src = API_URL + query; 
     document.head.insertBefore(s, null); 
    } 
+0

是的,这个工作,谢谢 – RashFlash