转到内容

编码食谱/HTML 编码

来自维基教科书,面向开放世界的开放书籍

将对象(通常是字符串)转换为 HTML 安全代码。

VBScript 解决方案

[编辑 | 编辑源代码]

可以转换字符串和记录集(转换为表格)。

function HTMLEncode (vInput)
  dim i
  if IsNull(vInput) then 
    HTMLEncode = vInput
    exit function
    end if
  select case TypeName(vInput)
    case "Recordset"
      HTMLEncode = _
        "<table border='1'>" & vbNewLine & _
        "  <tr>"
      for i = 0 to vInput.Fields.Count - 1
        HTMLEncode = HTMLEncode & "<th>" & HTMLEncode(vInput.Fields.Item(i).Name) & "</th>"
        next
      HTMLEncode = HTMLEncode & "</tr>" & vbNewLine
      if not vInput.BOF then vInput.MoveFirst
      while not vInput.EOF
        HTMLEncode = HTMLEncode & "  <tr>"
        for i = 0 to vInput.Fields.Count - 1
          if IsNull(vInput.Fields.Item(i).Value) then
            HTMLEncode = HTMLEncode & "<td>&nbsp;</td>"
          else
            HTMLEncode = HTMLEncode & "<td>" & HTMLEncode(vInput.Fields.Item(i).Value) & "</td>"
            end if
          next
        HTMLEncode = HTMLEncode & "</tr>" & vbNewLine
        vInput.MoveNext
        wend
      if not vInput.BOF then vInput.MoveFirst
      HTMLEncode = HTMLEncode & _
        "</table>" & vbNewLine
    case else
      HTMLEncode = vInput
      HTMLEncode = Replace(HTMLEncode, chr(0), "")
      HTMLEncode = Trim(Server.HTMLEncode(HTMLEncode))
      HTMLEncode = Replace (HTMLEncode, "'", "&#39;")
      HTMLEncode = Replace (HTMLEncode, "<", "&lt;")
      HTMLEncode = Replace (HTMLEncode, ">", "&gt;")
      HTMLEncode = Replace (HTMLEncode, "  ", "&nbsp; ")
      HTMLEncode = Replace (HTMLEncode, chr(10), "<br>" )
    end select
  end function
华夏公益教科书