User:Mike Dillon/Scripts/params.js: Difference between revisions

Content deleted Content added
functions for getting URL parameters for current request
 
m change unescape to decodeURIComponent
 
(4 intermediate revisions by the same user not shown)
Line 1:
/* <pre><nowiki> */
 
// Getfunction allgetParameterMap(url): Parses a URL parametersand fromextracts the query string parameters;
// if no URL is provided, uses the current URL. Caches parsed parameters between invocations.
var getParameterMap = (function () {
// URL parameters cache: key=url, value=paramMap
var params = {};
ifvar (___location.search)urlParamMaps = {};
// Trim the initial "?" and split on "&"
var kvs = ___location.search.replace(/^\?/, "").split("&");
for (var i in kvs) {
var kv = kvs[i].split("=", 2);
var key = kv[0], value = kv[1];
 
return iffunction (!params[key]url) {
// If no URL is passed in, use params[key]the =current [];page's URL
if (!url) }{
url = ___location.href;
}
 
// If the parameters for this URL have already been parsed, return them
params[key].push(value);
if (urlParamMaps[url]) return urlParamMaps[url];
 
// Set up a new map for the parameters to be parsed
var paramsparamMap = {};
 
// Split the URL from the query string
var search = url.split("?", 2)[1];
if (search) {
// Split query string on "&"
var kvs = ___location.search.replace(/^\?/, "").split("&");
for (var i in kvs) {
// Split each key-value pair on the equals sign
var kv = kvs[i].split("=", 2);
var key = kv[0], value = kv[1];
var value = decodeURIComponent(kv[1]);
 
// On the first occurence of a key, seed an empty array into paramMap
if (!paramMap[key]) {
paramMap[key] = [];
}
 
// Push the new value onto the value list for the key in paramMap
params paramMap[key].push(value);
}
}
}
 
// Cache the paramMap to avoid parsing for all parameter requests
return function () { return params };
urlParamMaps[url] = paramMap;
 
return paramMap;
};
})();
 
// function getParameterValues(key, url): Extracts the list of values for a particular key
function getParameter(key) {
// from the given URL; if no URL is provided, uses the current URL.
return getParameterValues(key)[0];
// Returns null if the parameter was not in the URL.
function getParameterValues(key, url) {
return getParameterMap(url)[key];
}
 
// function getParameterValues(key, url): {Extracts the values for a particular key
// from the given URL; if no URL is provided, uses the current URL.
return getParameterMap()[key];
// If there is more than one value for the given key, the first value is returned.
// Returns null if the parameter was not in the URL.
function getParameter(key, url) {
returnvar values = getParameterValues(key, url)[0];
return values ? values[0] : null;
}
 
// function getParameterNames(url): Extracts the list of parameter {names
// from the given URL; if no URL is provided, uses the current URL.
function getParameterNames(url) {
var names = [];
for (var n in getParameterMap(url)) {
names.push(n);
}