Search code examples
asp-classicjscript

Class ASP with JavaScript - handle the condition when a query param in Request.QueryString is missing


Possible Duplicate:
Finding out if a URL param exists in JS-ASP

this may be very fundamental but,

in the code below, the if branch is to cover the abnormal situation which the hitting request miss the query parameter of "name", like http://foo.com/bar.asp?foo=bar

<%@ language="javascript" %>

<html>
<head>
    <title>Hello ASP!</title>
</head>
<body>
    <%
        if (Request.QueryString("name") == undefined)
        {
            Response.Write("oops, give me your name!");
        }
        else
        {
            Response.Write("Hello " + Request.QueryString("name") + "!");
        }
    %>
</body>
</html>

but the if branch was never entered. The else branch takes place every time, and I got "Hello undefined!" every time.

I`ve tried to replace the undefined with "" or null, but nothing changes.

I`ve searched around but got things talking about ASP.NET/C# and client-side JavaScript. Appreciate your help!

UPDATED:
HI guys, thanks for your concern! But I mean ASP leveraging JavaScript to do server-side programming. I`ve updated the codes above.


Solution

  • The most reliable way to check whether a parameter was passed or not is to check the Count property:

    if (Request.QueryString("name").Count === 0) {
        // do whatever...
    }
    

    This works because Request.QueryString(var) actually returns an array-like object that contains multiple values, if the same parameter is specified multiple times in the URL (e.g., http://example.com/test.asp?name=value1&name=value2). You can read more in the MSDN documentation:

    http://msdn.microsoft.com/en-us/library/ms524784%28VS.90%29.aspx