[JavaScript]一段把客户端的中文字串转换成UTF-8的代码

**[JavaScript]一段把客户端的中文字串转换成UTF-8的代码
** 开发ASP.NET,我经常要在客户端的 javascript 代码中使用window.location='WebForm1.aspx?Param1=中文字串'来跳转页面,但在跳转之前必须要把中文字串转换成UTF-8的代码,否则如果中文字串中间存在空格之类的字符就会引起问题。

实际上IE 5.5+,Netscape 6+,Mozilla中已经有了转换函数,即encodeURIComponent,但对于低版本的浏览器则需要一下代码。
/* ***************************
** Most of this code was kindly
** provided to me by
** Andrew Clover (and at doxdesk dot com)
** http://and.doxdesk.com/ ;
** in response to my plea in my blog at
** http://worldtimzone.com/blog/date/2002/09/24
** It was unclear whether he created it.
*/
function utf8(wide) {
var c, s;
var enc = "";
var i = 0;
while(i

 1<wide.length) (c="" c="wide.charCodeAt(i++);" handle="" if="" surrogates="" utf-16="" {="">=0xDC00 &amp;&amp; c&lt;0xE000) continue;   
 2if (c&gt;=0xD800 &amp;&amp; c&lt;0xDC00) {   
 3if (i&gt;=wide.length) continue;   
 4s= wide.charCodeAt(i++);   
 5if (s&lt;0xDC00 || c&gt;=0xDE00) continue;   
 6c= ((c-0xD800)&lt;&lt;10)+(s-0xDC00)+0x10000;   
 7}   
 8// output _value_   
 9if (c&lt;0x80) enc += String.fromCharCode(c);   
10else if (c&lt;0x800) enc += String.fromCharCode(0xC0+(c&gt;&gt;6),0x80+(c&amp;0x3F));   
11else if (c&lt;0x10000) enc += String.fromCharCode(0xE0+(c&gt;&gt;12),0x80+(c&gt;&gt;6&amp;0x3F),0x80+(c&amp;0x3F));   
12else enc += String.fromCharCode(0xF0+(c&gt;&gt;18),0x80+(c&gt;&gt;12&amp;0x3F),0x80+(c&gt;&gt;6&amp;0x3F),0x80+(c&amp;0x3F));   
13}   
14return enc;   
15} 
16
17var hexchars = "0123456789ABCDEF"; 
18
19function toHex(n) {   
20return hexchars.charAt(n&gt;&gt;4)+hexchars.charAt(n &amp; 0xF);   
21} 
22
23var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; 
24
25function encodeURIComponentNew(s) {   
26var s = utf8(s);   
27var c;   
28var enc = "";   
29for (var i= 0; i&lt;s.length; i++) {   
30if (okURIchars.indexOf(s.charAt(i))==-1)   
31enc += "%"+toHex(s.charCodeAt(i));   
32else   
33enc += s.charAt(i);   
34}   
35return enc;   
36} 
37
38function URLEncode(fld)   
39{   
40if (fld == "") return false;   
41var encodedField = "";   
42var s = fld;   
43if (typeof encodeURIComponent == "function")   
44{   
45// Use _javascript_ built-in function   
46// IE 5.5+ and Netscape 6+ and Mozilla   
47encodedField = encodeURIComponent(s);   
48}   
49else   
50{   
51// Need to mimic the _javascript_ version   
52// Netscape 4 and IE 4 and IE 5.0   
53encodedField = encodeURIComponentNew(s);   
54}   
55//alert ("New encoding: " + encodeURIComponentNew(fld) +   
56// "\n escape(): " + escape(fld));   
57return encodedField;   
58}</wide.length)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus