Created
February 22, 2010 11:51
-
-
Save Crydust/311028 to your computer and use it in GitHub Desktop.
getQueryStringParam js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<script src="jquery-1.4.js"></script> | |
<script> | |
/** | |
* @return null if param not found | |
* @return string if param found once | |
* @return array if param found more than once or name ends with "[]" | |
*/ | |
function getQueryStringParam(name) { | |
var result = null; | |
if (window.location.search !== '') { | |
var querystring = window.location.search.substring(1).replace(/\+/g, ' '); | |
var pairs = querystring.split('&'); | |
var isFound = false; | |
for (var i = 0; i < pairs.length; i += 1) { | |
var pair = pairs[i].split('='); | |
var key = decodeURIComponent(pair[0]); | |
if (key === name) { | |
var val = (pair.length === 2 ? decodeURIComponent(pair[1]) : key); | |
if (!isFound) { | |
isFound = true; | |
result = [val]; | |
} else { | |
result.push(val); | |
} | |
} | |
} | |
if (isFound && result.length === 1 && !/\[[0-9]*\]$/.test(name)) { | |
result = result[0]; | |
} | |
} | |
return result; | |
} | |
/** | |
* helper function | |
*/ | |
function printQueryStringParam (name) { | |
var result = ""; | |
var val = getQueryStringParam(name); | |
if (val === null) { | |
result = "null"; | |
} | |
else if (jQuery.isArray(val)) { | |
result = "[\n\t" + val.join(",\n\t") + "\n]"; | |
} | |
else { | |
result = val; | |
} | |
return result; | |
} | |
</script> | |
</head> | |
<body> | |
<form action="test.html" method="get"> | |
<p> | |
text <input type="text" name="text" | |
value="space: , plus:+, slash:/, backslash:\, amp:&, equals:=, less:<, greater:>"><br> | |
</p> | |
<p> | |
checkbox[]<br> | |
<input type="checkbox" name="checkbox[]" value="a" checked> a<br> | |
<input type="checkbox" name="checkbox[]" value="b" checked> b<br> | |
</p> | |
<p> | |
<input type="submit"> | |
</p> | |
</form> | |
<hr> | |
<pre> | |
<script> | |
document.write("text: "+printQueryStringParam("text")); | |
document.write("\ncheckbox[]: "+printQueryStringParam("checkbox[]")); | |
</script> | |
</pre> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment