[JavaScript]一段把用戶端的中文字串轉換成UTF-8的代碼

來源:互聯網
上載者:User
[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           escape(): " + escape(fld));
 return encodedField;
}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.