edit-article
Home
Up
Delete
Article Name:
Article Description:
an example of how-to read querystring values in your client side code using javascript
Chapter ID/Name:
Status:
Write
Writing
Written
Add Photo:
Owner ID:
Content:
use HTML
Edit Content
<h1 style="text-align: center;">read querystring values in js</h1> <h2>[WHAT]</h2> <ol> <li>] The SO article referenced below(#1) indicates several methods 1 can use to get/read querystring parameters values ...</li> <ol> <li>] the top rated and 'accepted as answer' method using vanilla js may not be the best answer, here are a couple of the others answers in the article</li> <li>] i like the OO approach by __ for the way it enables you to access the param values qs["paramater"], but IMO the codeblock is somewhat(obsfuc,unreadable) </li> <li>] i used a jq function submitted by community wiki based on work by Roshambo , see exa 2 below</li> <li>] it also points to a jq plugin that will do this, as well as several other answers(more jq plugin solutions) </li> <li>] 1 answer shows the 'obsfucated' code that google uses</li> <li>] 1 answer shows a performance analysis of using jq plugin code VS plain vanilla js code</li> </ol></ol> <h2>[WHY]</h2> <ol> <li>] reading values passed in a querystring is something you will commonly do</li> </ol> <h2>[WHERE]</h2> <ol> <li>] everywhere</li> </ol> <h2>[WHEN]</h2> <ol> <li>] almost always</li> </ol> <h2>[EXAMPLE]</h2> <ol> <li>var qs = (function(a) {</li> <li> if (a == "") return {};</li> <li> var b = {};</li> <li> for (var i = 0; i < a.length; ++i)</li> <li> {</li> <li> var p=a[i].split('=');</li> <li> if (p.length != 2) continue;</li> <li> b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));</li> <li> }</li> <li> return b;</li> <li>})(window.location.search.substr(1).split('&'));</li> </ol> <div><hr /></div> <ol> <li>$.urlParam = function(name, url){</li> <li> if(!url){</li> <li> url = window.location.href;</li> <li> }</li> <li> var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);</li> <li> if (!results)</li> <li> { </li> <li> return 0; </li> <li> }</li> <li> return results[1] || 0;</li> <li>}</li> </ol> <h2>[HOW-TO]</h2> <ol> <li><strong>] example 1</strong></li> <ol> <li>] var paramValue = qs["paramName"] - this returns the value that you want to read</li> </ol> <li><strong>] example 2</strong></li> <ol> <li>] var paramValue = $.urlParam(paramName,url)</li> </ol></ol> <h2>[REFERENCE]</h2> <ol> <li>] http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript</li> <li>] http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/ by </li> <li>] http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html</li> </ol> <h1 style="text-align: center;"> </h1>