2016-08-15 138 views
0

我有一个从外部web服务接收数据的angularjs应用程序。Javascript字符串编码Windows-1250到UTF8

我想我正在接收UTF-8字符串,但用ANSI编码。

比如我得到

KLMÄšLENÃ  

当我想显示

KLMĚLENÍ 

我试图使用decodeURIComponent将其转换,但不起作用。

var myString = "KLMÄšLENÃ"  
console.log(decodeURIComponent(myString)) 

我可能错过了一些东西,但我找不到什么。

感谢和问候, 埃里克

+0

'Äš'不能UTF-8作为'š'是' 0x0161'。实际上,用UTF8编码的'Ě'和'Í'分别是十六进制序列'0xC4 0x9A'和'0xC3 0x8D'。这里'0x9A' _单字节Introducer_和'0x8D' _Reverse Line Feed_都是不可打印的字符,所以'KLMĚLENÍ'mojibaked到UTF-8将看起来像'KLMÄLENÃ '在控制台中用' '_Replacement Character_。 – JosefZ

回答

1

您可以使用TextDecoder。 (BE提防某些浏览器不支持它!)

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代码用于模拟服务器端输出:

resp.setContentType("text/plain; charset=ISO-8859-1"); 
OutputStream os = resp.getOutputStream(); 
os.write("KLMĚLENÍ".getBytes("UTF-8")); 
os.close(); 
+0

Thx,这并不能解决我的问题,因为我必须使它在IE上运行,但我已经请求对web服务进行更改,以便为我解决问题。但是,在另一种情况下,您的解决方案似乎很好 – Eric