JavaScript字符串编码Windows-1250到UTF8 [英] Javascript string encoding Windows-1250 to UTF8
本文介绍了JavaScript字符串编码Windows-1250到UTF8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想我正在接收UTF-8字符串,但是以ANSI编码。
>例如我得到
KLMÄšLENÃ
当我想显示
KLMĚLENÍ
我试图使用decodeURIComponent进行转换,但不起作用。
var myString =KLMÄšLENÃ
console.log(decodeURIComponent(myString))
我可能错过了一些东西,但我找不到什么。
谢谢和关心,
Eric
解决方案
您可以使用 TextDecoder 。 (请注意,一些浏览器不支持它。)
var xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.responseType ='arraybuffer';
xhr.onload = function(){
if(this.status == 200){
var dataView = new DataView(this.response);
var decoder = new TextDecoder(utf-8);
var decodedString = decoder.decode(dataView);
console.log(decodedString);
} else {
console.error('Error while requests',url,this);
}
};
xhr.send();
用于模拟服务器端输出的Java servlet代码:
resp.setContentType(text / plain; charset = ISO-8859-1);
OutputStream os = resp.getOutputStream();
os.write(KLMĚLENÍ.getBytes(UTF-8));
os.close();
I've an angularjs app that receive data from an external webservice.
I think I'm receiving UTF-8 string but encoded in ANSI.
For example I get
KLMÄšLENÃ
When I want to display
KLMĚLENÍ
I've tried to use decodeURIComponent to convert it but that doesn't work.
var myString = "KLMÄšLENÃ"
console.log(decodeURIComponent(myString))
I'm probably missing something but I can't find what.
Thanks and regards, Eric
解决方案
You can use TextDecoder. (Be beware! some browser does not support it.)
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (this.status == 200) {
var dataView = new DataView(this.response);
var decoder = new TextDecoder("utf-8");
var decodedString = decoder.decode(dataView);
console.log(decodedString);
} else {
console.error('Error while requesting', url, this);
}
};
xhr.send();
Java servlet code for simulating server side output:
resp.setContentType("text/plain; charset=ISO-8859-1");
OutputStream os = resp.getOutputStream();
os.write("KLMĚLENÍ".getBytes("UTF-8"));
os.close();
这篇关于JavaScript字符串编码Windows-1250到UTF8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文