Tom*_*ner 5 javascript xmlhttprequest utf-8
我想从网上获取一份文件xmlHttpRequest
.然而,有问题的文字不是utf8(在这种情况下它是windows-1251,但在通用情况下,我肯定不知道).
但是,如果我使用responseType="text"
它,就好像字符串是utf8,忽略内容类型中的字符集(导致令人讨厌的混乱).
如果我使用'blob'(可能是我想要的最接近的东西),那么考虑到编码,我可以将其转换为DomString吗?
我实际上找到了一个可以满足我想要的API,从这里开始:
基本上,使用responseType="arraybuffer"
,从返回的标头中选择编码,并使用DataView
和TextDecoder
.它完全符合要求.
const xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.onload = function() {
const contenttype = xhr.getResponseHeader("content-type");
const charset = contenttype.substring(contenttype.indexOf("charset=") + 8);
const dataView = new DataView(xhr.response);
const decoder = new TextDecoder(charset);
console.log(decoder.decode(dataView));
}
xhr.open("GET", "https://people.w3.org/mike/tests/windows-1251/test.txt");
xhr.send(null);
Run Code Online (Sandbox Code Playgroud)
fetch("https://people.w3.org/mike/tests/windows-1251/test.txt")
.then(response => {
const contenttype = response.headers.get("content-type");
const charset = contenttype.substring(contenttype.indexOf("charset=") + 8);
response.arrayBuffer()
.then(ab => {
const dataView = new DataView(ab);
const decoder = new TextDecoder(charset);
console.log(decoder.decode(dataView));
})
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
806 次 |
最近记录: |