Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  122] [ 2]  / answers: 1 / hits: 21157  / 5 Years ago, thu, march 21, 2019, 12:00:00

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.



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


More From » utf-8

 Answers
5

The response's text() function always decodes the payload as utf-8.


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.


Using your example it should be:


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

Notice that I'm using iso-8859-1 as decoder.


Credits: Schneide Blog


[#52381] Monday, March 18, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emileef

Total Points: 724
Total Questions: 108
Total Answers: 102

Location: Romania
Member since Sun, Dec 20, 2020
4 Years ago
;