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

StackOverflow https://stackoverflow.com//questions/10673597

  •  12-12-2019
  •  | 
  •  

Question

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.

Was it helpful?

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

OTHER TIPS

Perhaps this would work for you:

<script type="text/javascript">
// access the server-side response 
// and store it in a javascript variable
var myQueryString = '<%= Request.QueryString("name") %>';

// now write to the document using javascript only
if (myQueryString === "" ) {
   document.write("oops, give me your name!");
} else {
   document.write("Hello " + myQueryString + "!");
}
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top