1

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

Matt Briggs
42.4k17 gold badges103 silver badges128 bronze badges
asked Apr 13, 2010 at 5:25

2 Answers 2

1

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.

answered Apr 13, 2010 at 5:35
Sign up to request clarification or add additional context in comments.

1 Comment

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

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();
answered Apr 13, 2010 at 5:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.