When we use XMLHttpRequest to get the text content, if the server returned is GBK (or gb2312 and other non-UTF8 encoded) content, then get a bunch of garbled, how to convert to the default UTF8 encoded text in the browser?
In fact, if you are using Chrome or Firefox browser, it is very simple, you can use the browser built-in object Textdecoder to convert.
JavaScript Sample code:
if (' Textdecoder ' in window) { var files = { ' gbk.txt ': ' GBK ' }; Object.keys (Files). ForEach (function (file) { fetchanddecode (file, Files[file]);} ); } else { Console.error (' Your browser does not support the Encoding API. '); } function Fetchanddecode (file, encoding) { var xhr = new XMLHttpRequest (); Xhr.open (' GET ', file); Xhr.responsetype = ' Arraybuffer '; Xhr.onload = function () { if (this.status = =) { var dataView = new DataView (this.response); var decoder = new Textdecoder (encoding); var decodedstring = Decoder.decode (DataView); Console.info (decodedstring); } else { Console.error (' Error while requesting ', file, this); } }; Xhr.send (); }
In fact, not just GBK, as long as the browser-supported encoding (see link 3), can be easily converted.
Reference:
1. Https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
2. Easier ArrayBuffer String conversion with the Encoding API
3. https://encoding.spec.whatwg.org/
In-browser JavaScript conversion GBK text to UTF8 encoding (Chrome, Firefox only)