通过 AJAX/innerHTML 显示部分 Unicode 编码的数据

发布于 2024-07-24 22:14:25 字数 415 浏览 4 评论 0原文

我试图通过 AJAX 调用从服务器获取一些数据,然后使用 responseDiv.innerHTML 显示结果。 来自服务器的数据部分使用 Unicode 元素进行编码,例如:za\u010Dat test。 通过设置响应 div 的innerHTML,这将按原样显示。 也就是说,Unicode 不会转换为浏览器中的实际表示形式。

包含页面的字符集设置为 UTF-8。 我已经尝试了大多数其他方法,例如将 unicode 表示形式转换为 HTML 实体,但这似乎也不起作用。

我还应该提到,来自服务器的文本也混合了 HTML 标签。 HTML 标签得到了应有的尊重。 例如,如果来自服务器的文本为 Bold this!,则文本将以粗体显示。

任何帮助表示赞赏。

维克拉姆

I am trying to get some data from the server via an AJAX call and then displaying the result using responseDiv.innerHTML. The data from the server comes partially encoded with Unicode elements, like: za\u010Dat test. By setting the innerHTML of the response div, this just displayed as is. That is, the Unicode is not converted to an actual representation in the browser.

The charset of the containing page is set to UTF-8. I have tried most other things, like converting the unicode representation to HTML entities, but that doesn't seem to work either.

I should also mention that the text coming from the server has HTML tags intermixed as well. The HTML tags are honored as they should be. For example, if the text from the server comes as <b>Bold this!</b>, the text is bolded.

Any help appreciated.

Vikram

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

手心的温暖 2024-07-31 22:14:25

您可以将“\u010D”替换为“č”吗?

AFAIK 如果您设置innerHTML,来自服务器的HTML 标签应该可以工作。

这对我有用:

document.getElementById('info').innerHTML = "č <b>Bold this</b>";

顺便说一句 - 你可以使用 Fiddler 或 Firebug 之类的东西来确保你从服务器得到你期望的东西。

更新:使用正则表达式查找 unicode 字符并将其替换为 HTML 实体:

$.get('data.txt', function(data) {
    data = data.replace(/\\u([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])/g, '&#x$1$2$3$4;');
    document.getElementById('info').innerHTML = data;
});

Can you replace '\u010D' with 'č'?

AFAIK the HTML tags coming from the server should work if you are setting the innerHTML.

This works for me:

document.getElementById('info').innerHTML = "č <b>Bold this</b>";

BTW - you can use something like Fiddler or Firebug to ensure you are getting what you expect from the server.

Update: use regular expressions to find and replace the unicode characters with HTML entities:

$.get('data.txt', function(data) {
    data = data.replace(/\\u([0-9A-F])([0-9A-F])([0-9A-F])([0-9A-F])/g, '&#x$1$2$3$4;');
    document.getElementById('info').innerHTML = data;
});
咋地 2024-07-31 22:14:25

只需将 unicode 文字直接转换为字符即可:

'H\u0065\u006Clo, world!'.replace(/\u([0-9a-fA-F]{4})/, function() {

    return String.fromCharCode(parseInt(arguments[1],16));

<代码>});

Just convert the unicode literals to characters directly:

'H\u0065\u006Clo, world!'.replace(/\u([0-9a-fA-F]{4})/, function() {

    return String.fromCharCode(parseInt(arguments[1],16));

});

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文