问题描述
我正在尝试使用 Fetch 将一些数据带入屏幕,但是一些字符显示出奇怪的符号,我认为这与转换特殊字符有关.
I'm trying to use Fetch to bring some data into the screen, however some of the characters ares showing a weird sign which I believe has something to do with converting special chars.
在服务器端调试或在浏览器上调用 servlet 时,问题不会发生,因此我认为问题出在我的 JavaScript 上.请看下面的代码:
When debugging on the server side or if I call the servlet on my browser, the problem doesn't happen, so I believe the issue is with my JavaScript. See the code below:
var myHeaders = new Headers();
myHeaders.append('Content-Type','text/plain; charset=UTF-8');
fetch('getrastreiojadlog?cod=10082551688295', myHeaders)
.then(function (response) {
return response.text();
})
.then(function (resp) {
console.log(resp);
});
我认为这可能是一些细节,但我还没有设法找出发生了什么.所以欢迎任何提示谢谢
I think it is probably some detail, but I haven't managed to find out what is happening. So any tips are welcome Thx
推荐答案
response 的 text() 函数总是将 payload 解码为 utf-8.
The response's text() function always decodes the payload as utf-8.
如果您想要其他字符集中的文本,您可以使用 TextDecoder 转换 响应缓冲区 (NOT文本)转换为具有所选字符集的解码文本.
If you want the text in other charset you may use TextDecoder to convert the response buffer (NOT the text) into a decoded text with chosen charset.
使用您的示例应该是:
var myHeaders = new Headers();
myHeaders.append('Content-Type','text/plain; charset=UTF-8');
fetch('getrastreiojadlog?cod=10082551688295', myHeaders)
.then(function (response) {
return response.arrayBuffer();
})
.then(function (buffer) {
const decoder = new TextDecoder('iso-8859-1');
const text = decoder.decode(buffer);
console.log(text);
});
请注意,我使用 iso-8859-1
作为解码器.
Notice that I'm using iso-8859-1
as decoder.
致谢:施耐德博客
这篇关于JavaScript Fetch:有编码问题的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!