繁体   English   中英

无法显示来自unicode JSON响应的表情符号

[英]Unable to display emoji from unicode JSON response

<!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": []
  }
}

WeekAPI输出

第一种情况

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

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

工作正常

但当

第二个场景从api 检索标记值(值与上面相同)

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

它无法显示表情符号。 它是显示文字。

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

只有在引号之间硬编码的unicode字符串时,javascript才会解释unicode。

所以我使用eval函数并在下面的代码片段中创建解释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 );
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM