views:

42

answers:

2

How can we collect a query string value in javascript. my script is like follows http://192.168.10.5/study/gs.js?id=200 here i want to collect the id value in my gs.js script file. For this i am using

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
var string_value = getQuerystring('id');
alert(string_value);

But it is not getting..Please anybody can correct me.Please

+1  A: 

From my programming archive:

function querystring(key) {
  var re = new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
  var r = [], m;
  while ((m = re.exec(document.location.search)) != null) r[r.length] = m[1];
  return r;
}

The function returns the found values as an array with zero or more strings.

Usage:

var values = querystring('id');
if (values.length > 0) {
  // use values[0] to get the first (and usually only) value
  // or loop through values[0] to values[values.length-1]
}

or:

var string_value = querystring('id').toString();
Guffa
A: 

This function gets the query string of the page hosting this script: it relies on window.location.href. It seems that http://192.168.10.5/study/gs.js?id=200 is the address of the script itself and not the page. In order to do this you will need to first obtain this address by looking at the script tags in your document and then slightly modify the previous function to take an additional parameter representing the url and not relying on window.location.href.

Darin Dimitrov
Or - have the server side inject `var myid=200;` into the javascript code it serves for `gs.js?id=200`
gnarf