http://www.example.org/search?q=example&another=test&again=more
How can I create three sepearate variables in jQuery with the values example, test, and more?
In other words, how can I extract a query from a URL based on its position (first, second, third, etc.) in the URL or based on the &another= part (not sure what it's called) of the query?
Answer
I use this method:
var query        = window.location.split('?')[1]; // or http://www.example.org/search?q=example&another=test&again=more
var query_obj    = unserialize(query);
function unserialize(query) {
    var pair, params = {};
    query = query.replace(/^\?/, '').split(/&/);
    for (pair in query) {
        pair = query[pair].split('=');
        params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return params;
}
So you'll have your variables in the query_obj like this: query_obj.test
I found the function over the internet a while ago so I can't provide a link. Sorry and thanks to whoever published it first.
No comments:
Post a Comment