2016-10-01 61 views
2
<!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响应数据无法从Unicode JSON响应显示表情符号

{ 
    "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 output

第一场景存储到tag_value可变

表情符号的

Unicode值

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

工作正常

但当

第二场景 检索来自API标签值(值同上)在txtResponse部分使用$("#txtResponse").html(data.schedule.friday[0].tag);

显示。

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

+0

你能不能更新完整的json示例文章 – Aravind

+0

文章更新:) – asissuthar

+1

问题出在服务器端,它实际上是用字母'u'和反斜杠返回字符串。试图在JS消费者身上取消扩张可能会很脆弱(尤其是使用糟糕的eval)。这在源头上得到了更好的解决。 – bobince

回答

1

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

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

所以我用eval功能和创建下面的代码片段来解释unicode数据运行时。

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

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

找到另一种解决方案

在服务器侧进行打印响应于与\在JSON

$response = json_encode($result); 

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

在客户端替换\\之前刚刚添加str_replace功能

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