tomhoppe.com

Racing, Web Development, Photography, and Beer...Stuff that matters.

Tuesday, July 17, 2007

Querystring parsing

Here is a snippet that will pull out and parse out the query string using JS. It separates the query string into two arrays. One with the variable names and the other with the values. You can then loop through the arrays to get your information. This script is useful if you have lots of variables in your querystring, or are not sure what is going to be coming in. I also have another snippet which just grabs the value of one variable instead.

function QueryString(key){
  var value = null;
  for (var i=0;i<QueryString.keys.length;i++) {
    if (QueryString.keys[i]==key)  {
      value = QueryString.values[i];
      break;
    }
  }
  return value;
}

QueryString.keys = new Array();
QueryString.values = new Array();

function QueryString_Parse(){
  var query = window.location.search.substring(1);
  var pairs = query.split("&");
 
  for (var i=0;i<pairs.length;i++) {
    var pos = pairs[i].indexOf('=');
    if (pos >= 0)  {
      var argname = pairs[i].substring(0,pos);
      var value = pairs[i].substring(pos+1);
      QueryString.keys[QueryString.keys.length] = argname;
      QueryString.values[QueryString.values.length] = value;  
    }
  }
}

QueryString_Parse();

Labels: ,

0 Comments:

Post a Comment

<< Home