I have a website and want to display text. The text is in German and comes from a JSON data set I have. This is retrieved from a localhost API URL for now. The German words have the special characters replaced with HTML encoded ones. For example, erz?hlt is saved in the JSON data as erzählt. When I make the textContent of my paragraph tag to the JSON German text, the HTML encoding does not work. It does work however if I just copy and paste it manually in. How can I trigger the encoding to work and have it show correctly?
Code:
Gets random German word from JSON API, puts text into paragraph. Encoding issue.
erzählt is shown instead of erz?hlt .
JSON example:
{ "id": "32", "ename": "Smile.", "gname": "Lächeln!" }
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<h4>German:</h4>
<div>
<p id="gname">
</div>
<script>
const api_url = 'http://localhost:3000/fyp/api/grandom.php';
async function getData() {
const repsonse = await fetch(api_url);
const data = await repsonse.json();
var i = Math.floor((Math.random() * 16534) + 0);
const { gname, ename } = data[i];
document.getElementById('gname').textContent = gname;
document.getElementById('ename').textContent = ename;
}
getData();
</script>
Any help or advice appreciated. If anything needs explaining please let me know.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…