Finding out if a URL param exists in JS-ASP

纵饮孤独 提交于 2019-12-01 11:12:11

问题


I am editing other people's code, 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.)


回答1:


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.




回答2:


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
}



回答3:


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"; }
%>


来源:https://stackoverflow.com/questions/3908934/finding-out-if-a-url-param-exists-in-js-asp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!