Ever see or write JScript code in an ASP page like the following?
var str = Request.QueryString("param") + "";
Appending an empty string looks silly, doesn’t it?
What’s going on here is that the programmer needs the str
variable to be a JavaScript String object. Appending an empty string forces a type coercion.
I like using JScript on the server but integration with COM objects is clearly rougher in JScript than in VBScript. One of the contributing factors to the disparity in supporting COM is that VBScript essentially uses COM’s type system while JScript has its own type system in addition to supporting COM types.
The ASP intrinsic objects (Server, Application, Session, Request, and Response) are all COM objects. Request.QueryString("param")
returns a COM VARIANT containing a string. In VBScript the only way to represent a string is as a COM VARIANT string. In JScript, however, a COM VARIANT string is treated as a generic Object object not a String object. You need a String object though, if you want to call methods like split() or indexOf().
There are better ways to get a String than appending an empty string literal. You could, for example, use a cast:
var str = String(Request.QueryString("param"));
or use the item property:
var str = Request.QueryString("param").Item;
Request.QueryString is one of several collections provided by the ASP intrinsic objects. Weirdly the collections do not all behave the same way. Here’s a cheat sheet for the major collections:
Collection | To get a JavaScript String object | Return value if key doesn’t exist |
---|---|---|
Application.Contents | Application.Contents(key) | undefined |
Session.Contents | Session.Contents(key) | undefined |
Request.Cookies | Request.Cookies(key).Item | empty string |
Request.Form | Request.Form(key).Item | undefined |
Request.QueryString | Request.QueryString(key).Item | undefined |
Request.ServerVariables | Request.ServerVariables(key).Item | undefined |
Comments