JavaScript Library: getQueryStringParam()
Continuing on my series called the Javascript Library, I offer you more scripts that every web developer should have in their arsenal for every web project.
To start, how often does your project require you read items from a query string? It isn't a best practice but if you only had things in your arsenal that were best practices you'd never be able to work with other developers.
For this script you'll need a script already in my Javascript Library, getSubString(). Once you have that in your project this one is a synch:
getQueryStringParam()
function getQueryStringParam(paramName)
{
var qs = String(window.location);
var paramValue = getSubString(qs, paramName +'=', '&');
return paramValue;
}
That's right, 3 lines of code surrounded by the function wrapper, and only one input parameter:
- paramName
The name of the value you need from within your query string.
Now that I've shown you how, I really have to warn you: DON'T PASS THINGS AROUND IN YOUR QUERY STRING. Users have a tendency to do stupid things including typing randomly in query strings - if for some reason you have decided that this is the practice you want to do (or your boss insists it is) make sure you remember the following:
- Encrypt your Query string (try Mads Kristnsen's HttpModule)
- Build in error handling: your users WILL mess up the addresses and you don't want your code to puke on them
- Never, I will repeat this, NEVER put the username and password in your query string, not even encrypted. Amongst many other reasons, users who use public terminals will watch their password stolen over and over again.
Do you use the query string a lot? Why (or even, why not)?