asp,jquery,ajax中文乱码解决办法
aspweb服务器不支持 response.charset
所以采用编码
>1、只要在ajax中有数据提交时,如果页面编码不是utf-8的,都应该对提交的数据进行编码,js的编码函数为escape()
2、在服务器端页接收数据后进行解码,然后对数据进行相关的处理后再编码
3、返回到客户端后再解码
4、如果没有提交数据,而是直接从服务器端获取数据,那直接在服务器页面设置Response.Charset="gb2312"即可,不用再编码解码
vbscript中分别对应js中的escape()和unescape()函数
程序代码
<%
'与javascript中的escape()等效
Function VbsEscape(str)
dim i,s,c,a
s=""
For i=1 to Len(str)
c=Mid(str,i,1)
a=ASCW(c)
If (a>=48 and a<=57) or (a>=65 and a<=90) or (a>=97 and a<=122) Then
s = s & c
ElseIf InStr("@*_+-./",c)>0 Then
s = s & c
ElseIf a>0 and a<16 Then
s = s & "%0" & Hex(a)
ElseIf a>=16 and a<256 Then
s = s & "%" & Hex(a)
Else
s = s & "%u" & Hex(a)
End If
Next
VbsEscape=s
End Function
'与javascript中的unescape()等效
Function VbsUnEscape(str)
Dim x
x=InStr(str,"%")
Do While x>0
VbsUnEscape=VbsUnEscape&Mid(str,1,x-1)
If LCase(Mid(str,x+1,1))="u" Then
VbsUnEscape=VbsUnEscape&ChrW(CLng("&H"&Mid(str,x+2,4)))
str=Mid(str,x+6)
Else
VbsUnEscape=VbsUnEscape&Chr(CLng("&H"&Mid(str,x+1,2)))
str=Mid(str,x+3)
End If
x=InStr(str,"%")
Loop
VbsUnEscape=VbsUnEscape&str
End Function
%>
'与javascript中的escape()等效
Function VbsEscape(str)
dim i,s,c,a
s=""
For i=1 to Len(str)
c=Mid(str,i,1)
a=ASCW(c)
If (a>=48 and a<=57) or (a>=65 and a<=90) or (a>=97 and a<=122) Then
s = s & c
ElseIf InStr("@*_+-./",c)>0 Then
s = s & c
ElseIf a>0 and a<16 Then
s = s & "%0" & Hex(a)
ElseIf a>=16 and a<256 Then
s = s & "%" & Hex(a)
Else
s = s & "%u" & Hex(a)
End If
Next
VbsEscape=s
End Function
'与javascript中的unescape()等效
Function VbsUnEscape(str)
Dim x
x=InStr(str,"%")
Do While x>0
VbsUnEscape=VbsUnEscape&Mid(str,1,x-1)
If LCase(Mid(str,x+1,1))="u" Then
VbsUnEscape=VbsUnEscape&ChrW(CLng("&H"&Mid(str,x+2,4)))
str=Mid(str,x+6)
Else
VbsUnEscape=VbsUnEscape&Chr(CLng("&H"&Mid(str,x+1,2)))
str=Mid(str,x+3)
End If
x=InStr(str,"%")
Loop
VbsUnEscape=VbsUnEscape&str
End Function
%>
来个演示:
客户端页:client.html
客户端页:client.html
程序代码
<script>
//jquery的post
$.post
(
'server.asp',
{
Act:'DoSubmit',
UserName:escape('西楼冷月'),//进行编码
WebSite:'www.chinacms.org'
},
function(data)
{
alert(unescape(data));//对返回数据进行解码
}
);
</script>
//jquery的post
$.post
(
'server.asp',
{
Act:'DoSubmit',
UserName:escape('西楼冷月'),//进行编码
WebSite:'www.chinacms.org'
},
function(data)
{
alert(unescape(data));//对返回数据进行解码
}
);
</script>
服务器端页:server.asp
程序代码
<%
Response.Charset="gb2312"
Dim UserName,WebSite
If Request.Form("Act")="DoSubmit" Then
UserName=Request.Form("UserName")
WebSite =Request.Form("WebSite")
'在服务器端解码
UserName=VbsUnEscape(UserName)//解码
'处理数据
'---省略数据处理部分
'数据处理后输出,先用VbsEscape()编码
'by www.chinacms.org
Response.Write VbsEscape(UserName)
End If
%>
Response.Charset="gb2312"
Dim UserName,WebSite
If Request.Form("Act")="DoSubmit" Then
UserName=Request.Form("UserName")
WebSite =Request.Form("WebSite")
'在服务器端解码
UserName=VbsUnEscape(UserName)//解码
'处理数据
'---省略数据处理部分
'数据处理后输出,先用VbsEscape()编码
'by www.chinacms.org
Response.Write VbsEscape(UserName)
End If
%>