javascript gb2312 转 utf8 有办法转吗?

2015-06-15 15:28:08 +08:00
 lmaq
远端数据返回是gb2312而本地js是utf8写到页面是乱码,如何用js脚本把gb2312编码转换成utf8 ?
4336 次点击
所在节点    程序员
7 条回复
otakustay
2015-06-15 16:36:04 +08:00
远端返回的时候在Content-Type头里加上charset应该就行了的
lmaq
2015-06-15 16:39:39 +08:00
@otakustay 主要是远端不可控啊,只能在本地操作了。
otakustay
2015-06-15 16:44:59 +08:00
@lmaq 如果是jsonp的话还行,script标签能加charset属性,如果是普通的xhr的话基本没什么办法了……
imn1
2015-06-15 16:50:27 +08:00
如果自己有后台环境,可以用后台做个跳板,js连接后台某个程序,这个程序把远端接收转码
oott123
2015-06-15 16:54:55 +08:00
https://www.npmjs.com/package/iconv-lite
Convert character encodings in pure javascript.

In-browser usage via Browserify (~180k gzip compressed with Buffer shim included).
tux
2015-06-15 18:21:14 +08:00
document.charset='gb2312';
iahu
2015-06-16 10:08:28 +08:00
var rstr2utf8 = function (input) {
var output = "";

for (var n = 0; n < input.length; n++) {
var c = input.charCodeAt(n);

if (c < 128) {
output += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
} else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}

return output;
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/198700

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX