Jump to content

variables in the URL


MrAdam

Recommended Posts

hi does anyone know if you can send vairables in the url for javascript, like php and asp/aspx ?for example a page like: "index.html?var=blah"then somehow return the values in js?? - thanksi've found a sort-of way of doing it... using HTML domto return the value after the #"document.write(location.hash);".. will work, but.. i still would like to know if there's a way of sending multiple variables.... ?

Link to comment
Share on other sites

One way I can think of already is if you take the location.hash as the complete string where all parameters would be and devide it by a sign, assigning each character as a member of an array. For exaple, if you had:#parameter1=value1&parameter2=value2you would need a function that would take everything after the hash as an argument and spilt it for each occurance of the & (with the split() method I guess). Then you'll need to assign each pair to an associative array. I'm not good into JS, so I can't offer you a code for that. I'm just giving you the logic to think about.

Link to comment
Share on other sites

This is a script I pulled of the net a while ago and it is great!

/* Client-side access to querystring name=value pairs	Version 1.2.3	22 Jun 2005	Adam Vandenberg*/function Querystring(qs) { // optionally pass a querystring to parse	this.params = new Object()	this.get=Querystring_get		if (qs == null)		qs=location.search.substring(1,location.search.length)	if (qs.length == 0) return// Turn <plus> back to <space>// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1	qs = qs.replace(/\+/g, ' ')	var args = qs.split('&') // parse out name/value pairs separated via &	// split out each name=value pair	for (var i=0;i<args.length;i++) {		var value;		var pair = args[i].split('=')		var name = unescape(pair[0])		if (pair.length == 2)			value = unescape(pair[1])		else			value = name				this.params[name] = value	}}function Querystring_get(key, default_) {	// This silly looking line changes UNDEFINED to NULL	if (default_ == null) default_ = null;		var value=this.params[key]	if (value==null) value=default_;		return value}

to use it you do this

var qs = new Querystring();var var1 = qs.get('var1');

Link to comment
Share on other sites

@aspnetguy this post definetly goes to my bookmarks :) .But one question. Does it get everything after a "?" the same way PHP does? I mean, it reads through for examplefile.html?foo=bar&god=me

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...