AJAX ASP

用 ASP 写 AJAX 接口:返回文本、XML、JSON,处理参数与错误。

Intermediate
Key PointsAJAX 接口只做一件事:读参数、算结果、以正确的 Content-Type 返回数据。

返回纯文本

ASP
<%
    Response.ContentType = "text/plain"
    Response.Charset = "UTF-8"

    Dim name
    name = Request.QueryString("name")
    If name = "" Then name = "World"

    Response.Write "Hello, " & name
%>
JavaScript
const res = await fetch('hello.asp?name=Ada');
document.getElementById('out').textContent = await res.text();
Output
Hello, Ada

返回 XML

ASP
<%
    Response.ContentType = "text/xml"
    Response.Charset = "UTF-8"
    Response.Write "<?xml version=""1.0"" encoding=""utf-8""?>"
    Response.Write "<users>"
    Do While Not rs.EOF
        Response.Write "<user id=""" & rs("id") & """>" & _
            Server.HTMLEncode(rs("name")) & "</user>"
        rs.MoveNext
    Loop
    Response.Write "</users>"
%>
JavaScript
const res = await fetch('users.asp');
const xml = new DOMParser().parseFromString(await res.text(), 'text/xml');
const names = [...xml.querySelectorAll('user')].map(u => u.textContent);

An XML response must start with <?xml ...?> on line one; any leading whitespace (BOM, blank line) makes DOMParser fail. The file cannot begin with a space.

返回 JSON

ASP
<%
    Response.ContentType = "application/json"
    Response.Charset = "UTF-8"

    Dim rows, i, first
    rows = Array(Array(1, "Ada"), Array(2, "Bob"))

    Response.Write "["
    For i = 0 To UBound(rows)
        If i > 0 Then Response.Write ","
        Response.Write "{""id"":" & rows(i)(0) & ",""name"":""" & _
            JsonEsc(rows(i)(1)) & """}"
    Next
    Response.Write "]"

    Function JsonEsc(s)
        Dim t
        t = Replace(s, "\", "\\")
        t = Replace(t, """", "\""")
        t = Replace(t, vbCr, "\r")
        t = Replace(t, vbLf, "\n")
        t = Replace(t, vbTab, "\t")
        JsonEsc = t
    End Function
%>
Output
[{"id":1,"name":"Ada"},{"id":2,"name":"Bob"}]

The main risk of hand-written JSON is incomplete escaping: miss one of backslash, quote, newline or a control character and JSON.parse fails entirely. Cover at least those five, or bring in a JSON library.

错误处理

ASP
<%
    Response.ContentType = "application/json"
    Response.Charset = "UTF-8"

    On Error Resume Next
    Dim data
    data = DoSomethingRisky()

    If Err.Number <> 0 Then
        Response.Status = "500 Internal Server Error"
        Response.Write "{""ok"":false,""error"":""服务器处理失败""}"
        ' 细节写日志
        Err.Clear
    Else
        Response.Write "{""ok"":true,""data"":""" & JsonEsc(data) & """}"
    End If
    On Error GoTo 0
%>

Return a non-2xx status on failure. A 200 with {ok:false} never reaches fetch's catch, forcing the frontend to inspect business fields — easy to forget.

防缓存

ASP
<%
    Response.CacheControl = "no-cache"
    Response.Expires = -1
    Response.AddHeader "Pragma", "no-cache"
%>
JavaScript
// 或者加时间戳,让每次请求的 URL 都不同
fetch(`data.asp?t=${Date.now()}`);

IE caches GET requests aggressively, serving the second request from cache without hitting the server. In development this looks like "the backend change had no effect"; no-cache or a timestamp parameter fixes it.

AJAX endpoints need the same injection and XSS defence. Values from Request in SQL are injection; in returned HTML fragments they are XSS. "Internal call" is not an excuse — anything a browser can request is public.

Friends & Partners