另一个URL中的URL的参数

Anc*_*tRo 2 javascript url jquery google-feed-api

这是一个易于理解的问题,我会一步一步地解释清楚一切.

我正在使用Google Feed API将RSS文件加载到我的JavaScript应用程序中.

如果需要,我有一个设置可以绕过Google缓存,我通过在我发送到Google Feed API的RSS文件链接末尾附加一个随机数来执行此操作.

例如,假设这是一个指向RSS的链接:

http://example.com/feed.xml
Run Code Online (Sandbox Code Playgroud)

为了绕过缓存,我在末尾添加一个随机数作为参数:

http://example.com/feed.xml?0.12345
Run Code Online (Sandbox Code Playgroud)

Google Feed API的整个网址如下所示,其中"q"是以上链接:

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http://example.com/feed.xml?0.12345
Run Code Online (Sandbox Code Playgroud)

这会绕过缓存并在大多数情况下运行良好,但是当我想要使用的RSS链接已经有参数时会出现问题.例如,像这样:

http://example.com/feed?type=rss
Run Code Online (Sandbox Code Playgroud)

像之前一样在最后添加数字会产生错误,并且不会返回RSS文件:

http://example.com/feed?type=rss?0.12345 // ERROR
Run Code Online (Sandbox Code Playgroud)

我尝试使用"&"附加随机数,如下所示:

http://example.com/feed?type=rss&0.12345
Run Code Online (Sandbox Code Playgroud)

这不再出错,并且正确返回了RSS文件.但是,如果我在Google Feed API网址中使用上述内容,则不再绕过缓存:

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http://example.com/feed.xml&0.1234
Run Code Online (Sandbox Code Playgroud)

这是因为"0.1234"被认为是整个URL的参数而不是"q"url的参数.因此,"q"仅保留为" http://example.com/feed.xml ",它不是唯一的,因此加载了缓存版本.

有没有办法让数字参数成为"q"网址的一部分,而不是整个网址的一部分?

Min*_*our 5

你需要encodeURIComponent像这样使用:

var url = 'http://example.com/feed.xml&0.1234';
document.getElementById('results').innerHTML = 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=' + encodeURIComponent(url);
Run Code Online (Sandbox Code Playgroud)
<pre id="results"></pre>
Run Code Online (Sandbox Code Playgroud)

您正在逃避本来会被视为URL的一部分的特殊字符.

要追加或创建queryString:

var url = 'http://example.com/feed.xml';
var randomParameter = '0.1234';
var queryString = url.indexOf('?') > - 1;
if(queryString){
    url = url + '&' + randomParameter;
} else {
    url = url + '?' + randomParameter;
}
//url needs to be escaped with encodeURIComponent;
Run Code Online (Sandbox Code Playgroud)