Search code examples
javascriptjqueryurlgoogle-feed-api

Parameter of an URL within another URL


This is a simple to understand question, I will explain step by step as to make everything clear.

I am using the Google Feed API to load an RSS file into my JavaScript application.

I have a setting to bypass the Google cache, if needed, and I do this by appending a random number at the end of the RSS file link that I send to the Google Feed API.

For example, let's say this is a link to an RSS:

http://example.com/feed.xml

To bypass the cache, I append a random number at the end as a parameter:

http://example.com/feed.xml?0.12345

The whole url to the Google Feed API would look like this, where "q" is the above link:

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http://example.com/feed.xml?0.12345

This bypasses the cache and works well in most cases but there is a problem when the RSS link that I want to use already has parameters. For example, like this:

http://example.com/feed?type=rss

Appending the number at the end like before would give an error and the RSS file would not be returned:

http://example.com/feed?type=rss?0.12345 // ERROR

I have tried using "&" to attach the random number, as so:

http://example.com/feed?type=rss&0.12345

This no longer gives an error and the RSS file is correctly returned. But if I use the above in the Google Feed API url, it no longer bypasses the cache:

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http://example.com/feed.xml&0.1234

This is because "0.1234" is considered a parameter of the whole url and not a parameter of the "q" url. Therefore "q" remains only as "http://example.com/feed.xml", it is not unique so the cached version is loaded.

Is there a way to make the number parameter be a part of the "q" url and not a part of the whole url?


Solution

  • You need to use encodeURIComponent like this:

    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);
    <pre id="results"></pre>

    You are escaping the special characters that would have been treated as part of the url otherwise.

    To append or create a 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;