javascript - JSON如何删除字符串的'字母
问题描述
我正在尝试'
从我的字符串中删除。怎么做?我正在使用带有 JSON 的 ajax。我的代码如下所示:
<html>
<body>
<p id="testHTML"></p>
</body>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$.getJSON("IOCounter.html", function(data) {
$('#testHTML').text(data.testHTML);
});
}, 2000); //Refreshrate in ms
});
</script>
</html>
在 testHTML 中,我从 IOCounter.html 获得字符串“HelloWorld”,但是当我在 index.html 中显示它时,我得到:
'HelloWorld'
现在我只想删除'
只得到HelloWorld。我需要做什么?
解决方案
返回的字符串是 HTML 编码的。要获得纯文本字符串,需要对其进行解码。
DOMParser(大多数浏览器都支持)可用于解码字符串,如下所示:
function htmlDecode(str) {
const doc = new DOMParser().parseFromString(str, "text/html");
return doc.documentElement.textContent;
}
使用它,您可以解码字符串,然后将其设置为#textHTML
.
$.getJSON("IOCounter.html", function(data) {
$('#testHTML').text(htmlDecode(data.testHTML));
});