473,756 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting URL parameters

I put together the following code to get the href's parameters :-

function GetParameters()
{
var arg = new Object();
var href = document.locati on.href;

if ( href.indexOf( "?") != -1)
{
var params = href.split( "?")[1];
var param = params.split("& ");

for (var i = 0; i < param.length; ++i)
{
var name = param[i].split( "=")[0];
var value = param[i].split( "=")[1];

arg[name] = value;
}
}
return arg;
}

document.open() ;

var args = GetParameters() ;
document.write( "date = " + args["date"] + "<BR>");
document.write( "time = " + args["time"] + "<BR>");

document.close( );

What I would like to do is return Undefined if there are no parameters, how
do I do this ?

Any other tips that maybe useful ?

Aaron
Jul 23 '06 #1
7 11281
Aaron Gray said the following on 7/23/2006 1:23 PM:
I put together the following code to get the href's parameters :-

function GetParameters()
{
var arg = new Object();
var href = document.locati on.href;

if ( href.indexOf( "?") != -1)
{
var arg = new Object();
Now, arg will only get defined if there is a ? in the URL.
But, arg should be an Array, not an Object.

var params = href.split( "?")[1];
var param = params.split("& ");

for (var i = 0; i < param.length; ++i)
{
var name = param[i].split( "=")[0];
var value = param[i].split( "=")[1];

arg[name] = value;
}
}
return arg;

Now, if arg gets defined, it will return arg. If it is not defined, then
undefined will get returned.
}

document.open() ;

var args = GetParameters() ;
document.write( "date = " + args["date"] + "<BR>");
document.write( "time = " + args["time"] + "<BR>");

document.close( );

What I would like to do is return Undefined if there are no parameters, how
do I do this ?
See above.
Any other tips that maybe useful ?
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 23 '06 #2
> if ( href.indexOf( "?") != -1)
> {

var arg = new Object();
Now, arg will only get defined if there is a ? in the URL.
okay.
But, arg should be an Array, not an Object.
okay, thats what I had before but it did not report a length when it had
elements so I presumed it was an Object.
> arg[name] = value;
So that is an associative Array not an Object ?

Aaron
Jul 23 '06 #3
Now, arg will only get defined if there is a ? in the URL.

Is there a better way of returning a non result than using undefined ?

The associative use of an Array appears to have no length, otherwise I would
use length as an indicator :(

Aaron
Jul 23 '06 #4
Aaron Gray said the following on 7/23/2006 4:01 PM:
>Now, arg will only get defined if there is a ? in the URL.

Is there a better way of returning a non result than using undefined ?

The associative use of an Array appears to have no length, otherwise I would
use length as an indicator :(
Aside from the fact that Javascript doesn't have an Associative Array,
you can check for it's existance:

if (arg){
return arg
}else{
return somethingElse
}

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 24 '06 #5

"Aaron Gray" <an********@gma il.comwrote in message
news:4i******** ****@individual .net...
>I put together the following code to get the href's parameters :-
>snip<
What I would like to do is return Undefined if there are no parameters,
how do I do this ?
I think Randy already covered this.

It's nothing more than personal preference but I never liked using
"undefined" for this kind of thing. I personally prefer returning null.
Practically there's very little difference (null and undefined both evaluate
to false) but with null you know that something's been set.

Undefined, on the other hand, could be a meaningful return from a function
or or the result of a typo calling the function. I like to be explicit in
my negatives. ;^) But then again "undefined" does seem very defensible as
the value asked for is, indeed, undefined.

I guess it all comes down to how the argument in your head goes - I wouldn't
steadfastly defend one or the other.
Any other tips that maybe useful ?
I just went through this same exercise a few weeks ago! Here's some things
I found/discovered/hated:

+) Remember that JavaScript has already pulled out the query string for you
into document.locati on.search. You don't really need to do the string
search for a question mark.

+) First off remember that you might get multiple parameters with the same
name: query string parameters do not have to be unique. Depending on your
browser and application you might get this if multiple form fields have the
same name for example. This can be a huge pain but isn't that hard to deal
with.

In my case the method that allows access to the parameters takes a
"ReturnStyl e" argument of "first" (the first value of that name), "last"
(the last value of that name), "List" (a comma-separated list of all the
values) or "Array" (the default - an array of all the values).

That way if you're SURE about the return you can call for the first value
and use it as a simple string... but in general it's no harder to just
access the first element of the returned array.

+) Personally I don't find the order of the paramters to be all that
important. The browser isn't required to send parameters in any specific
order. I ended up (like you did) with an object where each property name
was a named parameter. However, due to the issue above the value of that
property is an array of all the values with that name.

+) One note: remember that query strings may be URL encoded (have special
characters escaped). Use the JavaScript "unescape() " method to unencode
them for use - you should unescape both the parameter names and the values.

+) I'm not sure if you'll ever have the case... but I sometimes find myself
needing to parse a "foreign" query string - either one that was stored as
part of a URL someplace or constructed from scratch or something. You may
want to consider adding the capability to pass in a query string. In mine I
just added a "QueryStrin g" argument as the last one and did this in the
code:

if ( !QueryString ) {
QueryString = location.search ;
};

All it's saying is "If I got passed one, use it, otherwise use the one from
the current page".

If you'd like to take a look at my code feel free. It's open source and
ready to be poked and prodded:

http://www.depressedpress.com/Conten...ring/Index.cfm

The one feature I'd really like to add is the addition "search engine safe"
type URLs... but the variation amongst them is daunting. They're not "query
strings" but replacements for them which serve the same function when
translated by aware server-software. The point is that search engines will
often index these pages where they might not index a page with a query
string (which is presumed to be dynamic).

For example you might see this (which is generally parsable as "anything
after the first slash after the last period" but I need to do more
research - all of the server-side solutions I've seen look for specific
extensions making me wonder about the prevalence of periods after the file
extension. Also there really doesn't need to be a file extension at all.):

http://www.mysite.com/page.cfm/param.../param2/value2

It's a legal URL and encodes two parameters. However some implementations
use different delimiters like this:

http://www.mysite.com/page.cfm/param.../param2-value2

I've also seen this (which uses server-side mappings and URL rewriting to do
its stuff - no extension):

http://www.mysite.com/page/param1/value1/param2/value2

Or this (where the parameter names are omitted completely... apparently
being infered by the server application):

http://yourdomain.com/yourblog/nfblo...3/sample-post/

In any case it's ending up being a larger task than I first thought. ;^)

Jim Davis
Jul 24 '06 #6
"Jim Davis" <ne********@vbo ston.comwrites:
+) One note: remember that query strings may be URL encoded (have special
characters escaped). Use the JavaScript "unescape() " method to unencode
them for use - you should unescape both the parameter names and the values.
Also remember that spaces in the escaped string have been converted to
"+"'es, so to correctly decode the name or value, you can do:

unescape(string .replace(/\+/g," "))

....
if ( !QueryString ) {
QueryString = location.search ;
};
Personal preference (and nothing else) makes me prefer to write it:
QueryString = QueryString || location.search ;

The effect is the same, it's slightly shorter and slightly less
efficient if QueryString is not falsey.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 24 '06 #7
"Lasse Reichstein Nielsen" <lr*@hotpop.com wrote in message
news:4p******** **@hotpop.com.. .
"Jim Davis" <ne********@vbo ston.comwrites:
>+) One note: remember that query strings may be URL encoded (have special
characters escaped). Use the JavaScript "unescape() " method to unencode
them for use - you should unescape both the parameter names and the
values.

Also remember that spaces in the escaped string have been converted to
"+"'es, so to correctly decode the name or value, you can do:

unescape(string .replace(/\+/g," "))

...
> if ( !QueryString ) {
QueryString = location.search ;
};

Personal preference (and nothing else) makes me prefer to write it:
QueryString = QueryString || location.search ;

The effect is the same, it's slightly shorter and slightly less
efficient if QueryString is not falsey.
I am generating the query strings myself from a form on the page so I have
none of these problems.

Interesting though.

Aaron
Jul 24 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2253
by: Yoshitha | last post by:
Hi I am working on a web project. I have a InstallerClass in my project. While making setup ( using web setup template) for this web application, I have added a userinterface with 4 textboxs, and added assembly to CustomActions-->Install
15
2972
by: sara | last post by:
Hi I'm pretty new to Access here (using Access 2000), and appreciate the help and instruction. I gave myself 2.5 hours to research online and help and try to get this one, and I am not getting it. Simple database: I want to have a user enter Supply Orders (just for tracking purposes) by Item. The user may also enter a new item - "new" is a combination of Item, PartNumber and Vendor - they could have the
1
3409
by: Julia | last post by:
Hi, I have been asked this before but I think that I didn't explain myself well I am using exception and logging and I would like to log the parameters which was passed to the function whenever an exception was occurred,again,I want to emphasize that I am the owner of the code. I can see that idlasm can view the content of an assembly so I wonder why my
0
1568
by: Dica | last post by:
i'm getting an error when trying set my dataAdapter's selectCommand. the sqlStatement is a storedProc which takes parameters, so it's constructed as: sqlSelectCommand1.CommandText = ""; sqlSelectCommand1.CommandType = System.Data.CommandType.StoredProcedure; sqlSelectCommand1.Connection = sqlConnection1; sqlSelectCommand1.Parameters.Add(new
2
8086
by: Martin Raychev | last post by:
Hi all, I have the following problem: I have a private method that returns a SqlDataReader. For this to work I have not to close the DB connection in the above method. I do this only to
6
1728
by: Brett | last post by:
Not sure what the problem is here... Trying to update from a datagrid to an access database using vb.net... Its not updating the database but Im not getting any errors... Here is my code... 'OleDbUpdateCommand1 Me.OleDbUpdateCommand1.CommandText = "UPDATE tblGifts SET gift = ?, name = ?, purchased = ? WHERE (autonum = ?) AND (gi" & _ "ft = ? OR ? IS NULL AND gift IS NULL) AND (name = ? OR ? IS NULL AND name IS NUL" & _
0
1179
by: Steve | last post by:
Hi All, I have a Python script that uses SOAPpy and I'm outputting all of the methods and info about the parameters... I'm having trouble getting information out of the __init__ parameter. My code : from SOAPpy import WSDL
4
2098
by: preeti13 | last post by:
Hi friends i have a probelm i am try to pass the value to the employeeid parameter but getting th error please help me how i can do this i am getting the error here is my code using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI;
2
2432
by: preeti13 | last post by:
Hi guys i am here with my another probelm please help me.trying insert the value into the data base but getting the null value error .I am getting thsi error Cannot insert the value NULL into column 'EmployeeID', table 'Accomplishments.dbo.Accomplishment'; column does not allow nulls. INSERT fails. The statement has been terminated. and my code is this using System; using System.Collections;
11
1473
by: Armin Zingler | last post by:
"Bill Schanks" <wschanks@gmail.comschrieb Try to execute lvMembers.beginupdate before filling and lvMembers.endupdate
0
9431
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9844
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9819
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6514
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.