2

I'm with a problem with accented words on a 'fetch'... I've tried so many things but nothing changed. Do you folks know how make this out?

The problem is, the accented words come in this value.label variable. I've tried putting the charset on the header, but nothing. The interesting thing is that the values are showed correctly on the request preview in the chrome's dev console.

This is the code I'm using:

fetch(url + params, {
    method: "get"
})
.then(resp => resp.json())
.then(options => {
    log(options.values());
    options.forEach(value => {
    self.append(`<option value="${value.valor}" >${value.label}</option>`);
    });
});

This is the response from the webserver:

[{"label":"Sassarica Sapatilhas ","value":492}, 
{"label":"Sassarica Sapatilhas - Av Paulista","value":1547}, 
{"label":"Sassarica Sapatilhas - São Carlos","value":505}]

This is what i'm getting in the page:

Sassarica Sapatilhas - S�o Carlos

And this is the link for the CodePen: https://codepen.io/fabioamorim/pen/MZOByK

  • 1
    the good thing is that we know for certain that your json response is utf-8 ( because it's json, cannot be anything else). so, what's the charset of your page? what your browser says about that? – Federkun Dec 31 '18 at 18:21
  • @Federkun, my page is UTF-8 too, as my browser says: `document.characterSet "UTF-8"` – Fábio Amorim Dec 31 '18 at 18:41
  • Plus, I've tested the code with jQuery ajax, and everything goes fine. What's the problem with `fetch`? – Fábio Amorim Dec 31 '18 at 18:42
  • what's the output if you do `${encodeURIComponent(value.label)}`? any chance this is a live page that we can see? – Federkun Dec 31 '18 at 18:49
  • I'll try to put it live in a codepen or something, just a moment. – Fábio Amorim Dec 31 '18 at 18:50
  • I've added the link for the project. – Fábio Amorim Dec 31 '18 at 19:03
  • Cool. The return content type of `listmenu_item.asp` is `text/html; Charset=iso-8859-1`. It should be utf-8 instead. So, on the server side, change it to utf-8, of change the charset of the page to wait for iso-8859-1 text. Just keep it consistent. – Federkun Dec 31 '18 at 19:08
  • Sadly I don't have access to the backend... And change the meta of my page does nothing :/ – Fábio Amorim Dec 31 '18 at 19:12
  • @Federkun , I've achieved some success by not using the `Body.json()` method. Using the `Body.arrayBuffer()` method, then making a `new TextDecoder("iso-8859-1")` and finally using the `JSON.parse(decoder.decode(arrayBuffer)`.... – Fábio Amorim Jan 01 '19 at 18:04
  • This means the `Body.json()` method can't handle very well this kind of _charset_ crusade hahaha – Fábio Amorim Jan 01 '19 at 18:05

0 Answers0