1

我有一个字符集为“Shift_JIS”的文本文件,该文件包含日文字符。然后我对该文件执行 ajax 请求,如下所示。

$.ajax({
    url: "demo.txt",
    success: function(result){
        alert(result);
    }}
);

但是警报中显示的数据不是有效的日文字符。相反,它显示了一些垃圾数据。即使我尝试设置响应标头字符集并且我在stackoverflow中已经做了很多以前的解决方案,但它没有奏效。任何人都可以帮我解决这个问题吗?

注:浏览器为 Internet Explorer

4

2 回答 2

0

您说您尝试更改字符集,您是否尝试将 contentType 更改为纯文本?:

$.ajax({
    /*...*/
    contentType: "text/plain; charset=Shift_JIS"
    /*...*/
})
于 2017-02-23T15:54:19.633 回答
0

您不能直接在 JavaScript 中将 Shift_JIS 文件读入字符串对象。您必须先将文件内容存储到二进制对象中,然后使用TextDecoder.

不幸的是,jQuery$.ajax()无法将响应主体处理为dataType: 'binary'开箱即用的二进制 ( )。所以你必须使用像 jQuery BinaryTransport这样的附加模块,或者像这样使用 XMLHttpRequest:

// ref. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
var oReq = new XMLHttpRequest();
oReq.open("GET", "demo.txt", true);
oReq.responseType = "arraybuffer"; // handle response body as binary
oReq.onload = function (oEvent) {
  if (oReq.response) {
    var sjisDecoder = new TextDecoder('shift-jis');
    alert(sjisDecoder.decode(oReq.response))  // Note: not oReq.responseText
  }
};
oReq.send(null);
于 2020-12-09T15:47:34.563 回答