2016-08-15 143 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