五分排列3软件园:请安心下载,绿色无病毒!

软件提交最近更新热门排行
您现在的位置:首页››编程教学››.NET编程››综合其他

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

2005-06-28 02:13作者:佚名来源:本站整理浏览:1589 评论:0
[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<wide.length) {
   c= wide.charCodeAt(i++);
   // handle UTF-16 surrogates
   if (c>=0xDC00 && c<0xE000) continue;
   if (c>=0xD800 && c<0xDC00) {
     if (i>=wide.length) continue;
     s= wide.charCodeAt(i++);
     if (s<0xDC00 || c>=0xDE00) continue;
     c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
   }
   // output value
   if (c<0x80) enc += String.fromCharCode(c);
   else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
   else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
   else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
 }
 return enc;
}

var hexchars = "0123456789ABCDEF";

function toHex(n) {
 return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
}

var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

function encodeURIComponentNew(s) {
 var s = utf8(s);
 var c;
 var enc = "";
 for (var i= 0; i<s.length; i++) {
   if (okURIchars.indexOf(s.charAt(i))==-1)
     enc += "%"+toHex(s.charCodeAt(i));
   else
     enc += s.charAt(i);
 }
 return enc;
}

function URLEncode(fld)
{
if (fld == "") return false;
var encodedField = "";
var s = fld;
if (typeof encodeURIComponent == "function")
{
 // Use javascript built-in function
 // IE 5.5+ and Netscape 6+ and Mozilla
 encodedField = encodeURIComponent(s);
}
else
{
 // Need to mimic the javascript version
 // Netscape 4 and IE 4 and IE 5.0
 encodedField = encodeURIComponentNew(s);
}
//alert ("New encoding: " + encodeURIComponentNew(fld) +
//  "\n\t   escape(): " + escape(fld));
return encodedField;
}


Tags:责任编辑:cvery
顶一下(60)
92.31%
    1. 剑网3插件剑网3超级宏插件

      剑网3超级宏可以说对于PVE党非常适用的输出宏插件,在打剑网3副本的时候可以说是很有用处,只要是记住相应的命令,就能够输出对应的操作,在此五分排列3软件园提供了剑网3超级宏插件的下载以及大量的剑网3插件,更有整理...

    文章评论 五分排列3下载QQ群:① 7551827使用手机微信搜索 微信号:xinyunshouyou 关注我们 有更多惊喜!!

    请自觉遵守互联网相关政策法规,评论内容只代表网友观点,与本站立场无关!
      验证码:     登录   注册
    网友评论