【问题标题】:Unable to display emoji from unicode JSON response无法从 unicode JSON 响应显示表情符号
【发布时间】:2017-02-10 00:25:55
【问题描述】:
<!DOCTYPE html>
<html>
<head>
    <title>WeekAPI</title>
    <meta charset="utf-8">
</head>
<body>
    Tag Value from Variable
    <h1 id="txtDisplay">Please Wait..</h1>

    Tag Value from API
    <h1 id="txtResponse">Please Wait..<h1>

    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

    <script>

        var tag_value = "\uD83D\uDE05\uD83D\uDE00\uD83D\uDE02\uD83D\uDE2C\uD83D\uDE10\uD83D\uDE0E";

        $("#txtDisplay").html(tag_value);


        var api = "http://week.esy.es/api?id=140393107018&institute=039&branch=07&semester=7&callback=?";

        $.getJSON(api, function(data) {
            //response tag value is same as tag_value variable
            $("#txtResponse").html(data.schedule.friday[0].tag);
        });   
    </script>
</body>
</html>

API 响应数据

{
  "ok": true,
  "message": "Successful.",
  "schedule": {
    "monday": [
      {
        "type": "lecture",
        "_id": 2,
        "start": "11:32 AM",
        "end": "11:32 AM",
        "teacher": "KPP",
        "subject": "Compiler Design",
        "tag": ""
      }
    ],
    "tuesday": [],
    "wednesday": [],
    "thursday": [],
    "friday": [
      {
        "type": "holiday",
        "_id": 2,
        "start": "09:30 AM",
        "end": "10:21 AM",
        "name": "\\u0928\\u0935\\u0930\\u093E\\u0924\\u094D\\u0930\\u093F",
        "tag": "\\uD83D\\uDE05\\uD83D\\uDE00\\uD83D\\uDE02\\uD83D\\uDE2C\\uD83D\\uDE10\\uD83D\\uDE0E"
      }
    ],
    "saturday": [],
    "sunday": []
  }
}

第一种情况

表情符号的unicode值存储到tag_value变量中

在 txtDisplay 部分使用$("#txtDisplay").html(tag_value); 显示。

它工作正常

但是当

第二种情况 从 api 获取标签值(值同上)

在 txtResponse 部分使用$("#txtResponse").html(data.schedule.friday[0].tag); 显示。

无法显示表情符号。而是显示文本。

【问题讨论】:

  • 你能用完整的 json 样本更新帖子吗
  • 帖子更新:)
  • 问题出在服务器端,它实际上是返回带有字母“u”和反斜杠的字符串。试图在 JS 消费者处解开它可能很脆弱(尤其是使用糟糕的eval)。这最好在源头固定。
  • 我修复了 api 服务器的问题。您可以在下面的答案中查看它并告诉我是否有任何改进。

标签: javascript html json unicode


【解决方案1】:

了解javascript的内部工作后得到解决方案。

javascript 仅在 unicode 字符串在引号之间硬编码时解释 unicode。

所以我使用eval 函数并在下面创建代码 sn-p 来解释 unicode 数据运行时。

function interpret(s) {
    return eval("(function(){ return '" + s + "'})()");
}  

$.getJSON(api, function(data) {
    $("#txtResponse").html( interpret( data.schedule.friday[0].tag ) );
});

找到另一个解决方案

在服务器端刚刚在打印响应之前添加了str_replace 函数以将 \\ 替换为 json 中的 \

$response = json_encode($result);

echo str_replace( '\\\\' , '\\' , $response);

在客户端

$.getJSON(api, function(data) {
    $("#txtResponse").html( data.schedule.friday[0].tag );
});

【讨论】:

  • eval("(function(){ return '" + s + "'})()").... 非常感谢@asissithar。你拯救了我的一天。来自我的 +1。
猜你喜欢
  • 2016-11-06
  • 2020-06-23
  • 2015-05-09
  • 2016-02-07
  • 2021-11-07
  • 2016-10-05
  • 1970-01-01
  • 2014-08-26
  • 2018-02-12
相关资源
最近更新 更多