开发者

Finding out if a URL param exists in JS-ASP

I am editing other people's cod开发者_StackOverflowe, written in server-side JS for ASP, and have run into a problem that probably has a very simple solution.

I'm outputting some code from a URL param like this:

<%=Request.QueryString("param")%>

The problem is that if the param doesn't exist, I need to do something else. So I tried:

<% 
  var param = Request.QueryString("param");
  if (!param) { param = "Some Default Value"; }
%>
<%=param%>

The problem is that the if never seems to evaluate to true, even when the URL param is missing. I'm guessing that the !image condition doesn't work here. What should my test condition be?

(Please forgo stern warnings about doing escaping of URL params to prevent XSS.)


The correct way to check whether a query string parameter exists is with the Count property:

<% 
  var param = Request.QueryString("param");
  if (param.Count === 0) { param = "Some Default Value"; }
%>
<%=param%>

According to the documentation for Request.QueryString,

The value of Request.QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING.

That's probably why the simple if (!param) check doesn't work.


This is what I do.

function qs(name) {
    var v = Request.QueryString(name),
        v2 = "x" + v + "x";
    if ((v2=="xundefinedx") && (v != "undefined")) {
        return null;
    }
    return v + ''; // force string
}


In JSP you have to use getParameter instead of QueryString

The code in JSP would be

<% 
  String param = request.getParameter("param");
  if (param.length() == 0) { param = "Some Default Value"; }
%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜