ASP 表单

GET 与 POST 表单、Request 取值、多值参数、中文编码。

Beginner
Key PointsGET 表单用 Request.QueryString 取,POST 表单用 Request.Form 取,用 Request("x") 可以两者通吃。

GET 表单

ASP
<form action="search.asp" method="get">
  关键词:<input type="text" name="q">
  <input type="submit" value="搜索">
</form>
ASP
<%
    Dim q
    q = Request.QueryString("q")
    If q <> "" Then
        Response.Write "你搜索的是:" & Server.HTMLEncode(q)
    End If
%>
Output
你搜索的是:asp

POST 表单

ASP
<form action="save.asp" method="post">
  姓名:<input type="text" name="name"><br>
  性别:<input type="radio" name="sex" value="m" checked>男
        <input type="radio" name="sex" value="f">女<br>
  爱好:<input type="checkbox" name="hobby" value="read">阅读
        <input type="checkbox" name="hobby" value="run">跑步<br>
  城市:<select name="city">
          <option value="bj">北京</option>
          <option value="sh">上海</option>
        </select><br>
  <input type="submit" value="提交">
</form>
ASP
<%
    Response.CodePage = 65001
    Response.Charset = "UTF-8"

    Dim name, sex, city, hobbies
    name = Request.Form("name")
    sex  = Request.Form("sex")
    city = Request.Form("city")
    hobbies = Request.Form("hobby")        ' 多值,返回逗号分隔的字符串

    Response.Write "姓名:" & Server.HTMLEncode(name) & "<br>"
    Response.Write "性别:" & sex & "<br>"
    Response.Write "城市:" & city & "<br>"
    Response.Write "爱好:" & hobbies & "<br>"
%>
Output
姓名:张三
性别:m
城市:bj
爱好:read, run

For a multi-select checkbox Request.Form("hobby") joins all values with , . To process them individually use Request.Form("hobby").Count with Request.Form("hobby")(i).

Request("x") 的取舍

ASP
<%
    ' 通吃 QueryString / Form / Cookies / ClientCertificate / ServerVariables
    Dim v
    v = Request("q")

    ' 明确来源更安全:只读表单,不会被 URL 参数覆盖
    v = Request.Form("q")
%>

Request("x") searches QueryString → Form → Cookies → ServerVariables. An attacker can override a form field with a URL parameter, so login and permission fields must use Request.Form explicitly.

中文乱码

ASP
<% @Language="VBScript" CodePage="65001" %>
<%
    Session.CodePage = 65001
    Response.CodePage = 65001
    Response.Charset = "UTF-8"
%>
SettingEffect
@CodePage=65001按 UTF-8 解析 .asp 文件本身
Session.CodePage请求参数按 UTF-8 解码
Response.CodePage响应内容按 UTF-8 编码
Response.Charset写进 Content-Type 头
All three must be 65001 or text garbles. The file itself must be saved as UTF-8 without BOM — with a BOM those bytes go out before any output and break Response.Redirect.

Friends & Partners