**[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 && c<0xE000) continue;
2if (c>=0xD800 && c<0xDC00) {
3if (i>=wide.length) continue;
4s= wide.charCodeAt(i++);
5if (s<0xDC00 || c>=0xDE00) continue;
6c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
7}
8// output _value_
9if (c<0x80) enc += String.fromCharCode(c);
10else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
11else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
12else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
13}
14return enc;
15}
16
17var hexchars = "0123456789ABCDEF";
18
19function toHex(n) {
20return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
21}
22
23var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
24
25function encodeURIComponentNew(s) {
26var s = utf8(s);
27var c;
28var enc = "";
29for (var i= 0; i<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)>