【问题标题】:url containing "&" does not work with google pagespeed api包含“&”的网址不适用于 google pagespeed api
【发布时间】:2017-09-27 14:19:10
【问题描述】:

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

示例(有效)

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

但是当我像这样更改网址时,它不会显示正确的结果

不起作用的示例

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

Api 忽略“&sub=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”视为自己的参数,因此将忽略它​​。

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

注意:我正在使用 pagespeed 示例代码进行测试,即https://developers.google.com/speed/docs/insights/v2/first-app

任何帮助将不胜感激

【问题讨论】:

  • 或许.join('&')
  • .join('&') 不起作用:(
  • 好吧,sub=890 不需要任何编码,但在您的代码中,您有一个完整的 URL 作为查询字符串,在尝试发送之前肯定需要 URL 编码。

标签: javascript google-pagespeed


【解决方案1】:

您需要使用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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    相关资源
    最近更新 更多