Teebone Ding Technical Blog

Django, Python, Javascript, Pig, and Hadoop.

Fetch URL Query String With a jQuery Plugin

Useful plugin for fetching URL parameters

Download the plugin here:

Include jQuery and this plugin in your HTML page:

1
2
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.url.min.js"></script>

The source code of the jquery plugin is here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
jQuery Url Plugin
 * Version 1.0
 * 2009-03-22 19:30:05
 * URL: http://ajaxcssblog.com/jquery/url-read-get-variables/
 * Description: jQuery Url Plugin gives the ability to read GET parameters from the actual URL
 * Author: Matthias Jäggli
 * Copyright: Copyright (c) 2009 Matthias Jäggli under dual MIT/GPL license.
*/
(function ($) {
 $.url = {};
 $.extend($.url, {
  _params: {},
  init: function(){
   var paramsRaw = "";
   try{
    paramsRaw =
     (document.location.href.split("?", 2)[1] || "").split("#")[0].split("&") || [];
    for(var i = 0; i< paramsRaw.length; i++){
     var single = paramsRaw[i].split("=");
     if(single[0])
      this._params[single[0]] = unescape(single[1]);
    }
   }
   catch(e){
    alert(e);
   }
  },
  param: function(name){
   return this._params[name] || "";
  },
  paramAll: function(){
   return this._params;
  }
 });
 $.url.init();
})(jQuery);

Using the plugin:

$.url.param(“PARAMETER_NAME”)

For instance, if you would like to fetch a parameter called “man” and the current page URL is http://example.com?man=dude, just call $.url.param("man") and it will return a string “dude” for you.

If the parameter name you denoted does not exist, it will return nothing (empty string).

$.url.paramAll()

To fetch all parameters from current URL, call $.url.paramAll() and it will return an array of all parameters.

Reference:

http://paladinprogram.blogspot.tw/2009/11/jquery-url.html

https://code.google.com/p/gantry/source/browse/trunk/root/js/jquery.url.min.js?r=1485

Comments