查明 JS-ASP 中是否存在 URL 参数

2022-01-16 00:00:00 asp-classic javascript jscript

我正在编辑其他人的代码,用 ASP 的服务器端 JS 编写,遇到了一个问题,可能有一个非常简单的解决方案.

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.

我正在从这样的 URL 参数中输出一些代码:

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%>

问题是 if 似乎永远不会评估为 true,即使 URL 参数丢失也是如此.我猜 !image 条件在这里不起作用.我的测试条件应该是什么?

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?

(请放弃关于转义 URL 参数以防止 XSS 的严厉警告.)

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

推荐答案

检查查询字符串参数是否存在的正确方法是使用 Count 属性:

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%>

根据 的文档Request.QueryString,

Request.QueryString(parameter) 的值是一个包含所有QUERY_STRING 中出现的参数值.

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

这可能是简单的 if (!param) 检查不起作用的原因.

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

相关文章