Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - HTML encoding/decoding issue, when using JS to get from JSON data sample

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&#228hlt. 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&#228hlt is shown instead of erz?hlt .

JSON example: { "id": "32", "ename": "Smile.", "gname": "L&#228cheln!" }

<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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your string contains HTML entities like &#228 then it isn’t text, it is HTML.

textContent expects you to pass plain text to it, not HTML source code.

Use innerHTML instead.

const value = "erz&#228hlt";
text.textContent = value;
html.innerHTML = value;
<div id=text></div>
<div id=html></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...