2017-10-15 14 views
2

xmlHttpRequest으로 웹에서 문서를 가져 오려고합니다. 그러나 문제의 텍스트는 utf8이 아닙니다 (이 경우 Windows-1251이지만 일반적인 경우에는 확실하지 않습니다).XMLHttpRequest로 utf8이 아닌 데이터 가져 오기

그러나 responseType="text"을 사용하면 콘텐츠 유형의 charset을 무시하고 문자열이 utf8 인 것처럼 처리합니다.

'blob'(아마도 내가 원한 것에 가장 가까운 것)을 사용한 경우 인코딩을 고려한 DomString으로 변환 할 수 있습니까?

+1

은'내용-type' 당신이 확신의 캐릭터 세트를 무시하고 서버가 제대로 등을 제공, 창-1251과 같은 파일을 읽고 올바른 내용 유형으로 응답합니까? 이 세 가지 중 누군가가 실패하면 알파벳 수프로 끝날 수도 있습니다. 단 하나의 바이트 만 브라우저에 도착하기도합니다. – Thomas

+0

'이 인코딩을 고려한 DomString으로 변환합니다.'api/lib를 인식하지 못합니다.하지만 최악의 경우 각 바이트를 적절한 char로 매핑 할 수 있습니다. – Thomas

답변

2

는 사실은 여기에서 내가 원하는 것을하는 API를 발견

https://developers.google.com/web/updates/2014/08/Easier-ArrayBuffer-String-conversion-with-the-Encoding-API

는 기본적으로, responseType="arraybuffer"를 사용하여 반환 된 헤더에서 인코딩을 선택하고, DataViewTextDecoder를 사용합니다. 그것은 정확히 필요한 것을 수행합니다.

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);

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)); 
 
     }) 
 
    })

1

'blob'(아마도 내가 원한 것에 가장 가까운 것)을 사용한 경우 인코딩을 고려한 DomString으로 변환 할 수 있습니까?

https://medium.com/programmers-developers/convert-blob-to-string-in-javascript-944c15ad7d52은 일반적으로 사용할 수있는 방법의 개요입니다. 원격 문서를 가져 오는 경우에 그 적용하려면

이처럼

:

const reader = new FileReader() 
 
reader.addEventListener("loadend", function() { 
 
    console.log(reader.result) 
 
}) 
 
fetch("https://people.w3.org/mike/tests/windows-1251/test.txt") 
 
    .then(response => response.blob()) 
 
    .then(blob => reader.readAsText(blob, "windows-1251"))

또는 대신 정말 XHR 사용하려면 : 나는 responseType="text"를 사용하는 경우는 문자열에서 문자 집합을 무시하고, UTF8 인 것처럼 취급합니다, 그러나

const reader = new FileReader() 
 
reader.addEventListener("loadend", function() { 
 
    console.log(reader.result) 
 
}) 
 
const xhr = new XMLHttpRequest() 
 
xhr.responseType = "blob" 
 
xhr.onload = function() { 
 
    reader.readAsText(xhr.response, "windows-1251") 
 
} 
 
xhr.open("GET", "https://people.w3.org/mike/tests/windows-1251/test.txt", true) 
 
xhr.send(null)

을 콘텐츠 유형

예. 무엇 그건 required by the Fetch spec합니다 (XHR 사양이 너무 의존 무엇 이것에 대한 어떤) 다음 Body 믹스 인을 구현

객체는 관련 패키지 데이터 알고리즘을 가지고, 바이트하는 유형mimeType를 제공 , 유형에 스위치 및 관련 단계를 실행합니다
...
텍스트
반환을 UTF-8 decode바이트에 실행 한 결과

+0

가져 오기 사양에서 해당 노트를 놓쳤습니다. 감사. xmlhttprequest를 사용하는 이유는 인코딩이 무엇인지 알아내는 것입니다. –