解決ASP中傳送中文參數(shù)亂碼的問題

2010-08-28 10:54:11來源:西部e網(wǎng)作者:

在網(wǎng)頁中,有時候會傳送一些中文參數(shù),但是在某些瀏覽器下(比如IE,在Firefox就是正常的),這些中文參數(shù)轉(zhuǎn)換就會出錯,會用到ASP中的URLEncode方法來解決這個問題。

比如傳送的參數(shù)為:

http://weste.net/?西部e網(wǎng)

直接發(fā)送可能在程序接受方就是亂碼,尤其在UFT-8的編碼下,所以我們發(fā)送前要先轉(zhuǎn)換一下

<% Response.Write "/?"&Server.URLEncode("西部e網(wǎng)") %>

轉(zhuǎn)換后就變成了

http://weste.net/?id=%E8%A5%BF%E9%83%A8e%E7%BD%91

發(fā)送過去接收的程序還要將%E8%A5%BF%E9%83%A8e%E7%BD%91這部分轉(zhuǎn)換回原來的代碼,這個時候ASP就沒有提供一個解碼的方法了,要我們自己寫一個:

<%
'Server.URLEncode(string)的解密函數(shù)
Function URLDecode(enStr)
   dim deStr,strSpecial
   dim c,i,v
     deStr=""
     strSpecial="!""#$%&'()*+,.-_/:;<=>?@[\]^`{|}~%"
     for i=1 to len(enStr)
       c=Mid(enStr,i,1)
       if c="%" then
         v=eval("&h"+Mid(enStr,i+1,2))
         if inStr(strSpecial,chr(v))>0 then
           deStr=deStr&chr(v)
           i=i+2
         else
           v=eval("&h"+ Mid(enStr,i+1,2) + Mid(enStr,i+4,2))
           deStr=deStr & chr(v)
           i=i+5
         end if
       else
         if c="+" then
           deStr=deStr&" "
         else
           deStr=deStr&c
         end if
       end if
     next
     URLDecode=deStr
End function
%>

接受的時候這樣寫:

<% name = URLEncode(Request("id")) %>

這樣就轉(zhuǎn)換過來了!

關鍵詞:ASP