utf-8页面,接收gbk参数, 或者 gbk 页面接收 utf-8 参数,或者...
很少会出现这样的参求,但有时候却是不得己。
本文介绍ASP接受不同编码传递的中文参数不产生乱码的方法。
<script language="jscript" runat="Server"> function decodeURL(str, cSet) { with (Server.CreateObject("ADODB.Stream")) { Type=2; Charset="iso-8859-1"; Open(); WriteText(unescape(str.replace(/\+/g, "%20"))); Position=0; Charset=cSet; str=ReadText(-1); Close(); } return str; } function getParameter(paramName, encodingForDecode, dictionary) { var values = []; dictionary.Item.replace(new RegExp("(?:^|&)" + paramName + "=([^&]*)", "gi"), function($, $1) { values.push(decodeURL($1, encodingForDecode)); }); return values; } </script> <%=getParameter("gbkParam", "GBK", Request.QueryString)%><br /> <%=getParameter("utfParam", "UTF-8", Request.QueryString)%><br />
VBScript 实现
测试地址:http://localhost/1.asp?gbkParam=%D6%D0%CE%C4%B0%A1&utfParam=%E4%B8%AD%E6%96%87%E5%95%8A
<% Class StringList Private dict, strName, i Private Sub Class_Initialize() Set dict = CreateObject("Scripting.Dictionary") i = 0 End Sub Public Property Get Count() Count = i End Property Public Property Let Name(newValue) strName = newValue End Property Public Property Get Name() Name = strName End Property Public Sub Add(strValue) i = i + 1 dict.Add i, strValue End Sub Public Default Property Get ToString() ToString = Me.Item(Empty) End Property Public Property Get Item(index) If Not IsEmpty(index) And IsNumeric(index) Then If index<1 Then Err.Raise -1, "StringList.Item", "下标越界" If index>i Then Err.Raise -1, "StringList.Item", "下标越界" Item = dict.Item(index) ElseIf i>0 Then Item = Join(dict.Items(), ", ") End If End Property End Class Function decodeURIComponent(str, cSet) With Server.CreateObject("ADODB.Stream") .Type = 2 .Charset = "iso-8859-1" .Open .WriteText UnEscape(Replace(str, "+", "%20")) .Position = 0 .Charset = cSet decodeURIComponent = .ReadText(-1) .Close End With End Function Function getParameter(name, cSet, dictionary) Dim match : Set getParameter = New StringList : getParameter.Name = name With New RegExp .Pattern = "(?:^|&)" & Server.URLEncode(name) & "=([^&]*)" .Global = True For Each match In .Execute(dictionary) getParameter.Add decodeURIComponent(match.Submatches.Item(0), cSet) Next End with End Function %> <%=getParameter("gbkParam", "GBK", Request.QueryString)%><br /> <%=getParameter("utfParam", "UTF-8", Request.QueryString)%><br /> <%=getParameter("utfParam", "UTF-8", Request.QueryString).Count%><br /> <%=getParameter("utfParam", "UTF-8", Request.QueryString).Item(1)%><br />
声明:如需转载,请注明来源于www.webym.net并保留原文链接:http://www.webym.net/jiaocheng/915.html