JavaScript使用的是Unicode编码,使用内置的encodeURIComponent,encodeURI,escape都是编码为Unicode的url编码,如果传递这些编码到gb2312或者gbk编码的页面,获取这写参数是就会出现乱码。
js有没有现成的类库可以直接将中文编码为gb2312或者gbk编码的,好传递到gb2312编码的页面。
有现成的js类库的,参考这个:js对中文进行gb2312/gbk编码解码
实际上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 c= wide.charCodeAt(i++);
// handle UTF-16 surrogates
if (c>=0xDC00 %26amp;%26amp; c if (c>=0xD800 %26amp;%26amp; c if (i>=wide.length) continue;
s= wide.charCodeAt(i++);
if (s=0xDE00) continue;
c= ((c-0xD800)< }
// output value
if (c else if (c>6),0x80+(c%26amp;0x3F));
else if (c>12),0x80+(c>>6%26amp;0x3F),0x80+(c%26amp;0x3F));
else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12%26amp;0x3F),0x80+(c>>6%26amp;0x3F),0x80+(c%26amp;0x3F));
}
return enc;
}
var hexchars = "0123456789ABCDEF";
function toHex(n) {
return hexchars.charAt(n>>4)+hexchars.charAt(n %26amp; 0xF);
}
var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
function encodeURIComponentNew(s) {
var s = utf8(s);
var c;
var enc = "";
for (var i= 0; 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;
}