Special characters (ë) in JSON-response

爱⌒轻易说出口 提交于 2020-01-03 03:40:13

问题


My database stores some texts which I have to get with AJAX. This is going well but only when it not contains special characters such as ë or ä. I found some articles about this topic which told me to change the charset of the AJAX-request, but none of these worked for me.

When I start firebug it said this about the headers:

Antwoordheaders (dutch for responseheaders)
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection close
Content-Length 94
Content-Type text/html; charset=ISO-8859-15
Date Wed, 26 Sep 2012 09:52:56 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Pragma no-cache
Server Apache
X-Powered-By PleskLin

Verzoekheaders (dutch for requestheaders)
Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Encoding gzip, deflate
Accept-Language nl,en-us;q=0.7,en;q=0.3
Authorization Basic c3BvdGlkczp6SkBVajRrcw==
Connection keep-alive
Content-Type text/html; charset=ISO-8859-15
Cookie __utma=196329838.697518114.1346065716.1346065716.1346065716.1; __utmz=196329838.1346065716.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHPSESSID=2h4vu8gu9v8fe5l1t3ad5agp86
DNT 1
Host www.spotids.com
Referer http://www.spotids.com/private/?p=16
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1

Both of the headers are talking about charset=ISO-8859-15 which should include characters like ë, but it doesn't work for me.

The code I used for this (PHP):

`$newresult = mysql_query($query2);    
    $result = array();
    while( $row = mysql_fetch_array($newresult))
    {
        array_push($result, $row);
    }
    $jsonText = json_encode($result);
    echo $jsonText;`

回答1:


  1. Make sure you set the headers to UTF-8:

    header('Content-Type: application/json; charset=utf-8');
    
  2. Make sure your connection to database is made with UTF-8 encoding before any queries:

    $query = mysql_query("SET NAMES 'UTF8'");
    
  3. As far as I know, JSON encodes any characters that cannot be represented in pure ASCII. And you should decode that JSON on response.

  4. Try to move to PDO as mysql_* functions are deprecated. Use this nice tutorial




回答2:


From JSON RFC-4627 : JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. Use mb_convert_encoding or iconv to change string encoding.

And send correct header:

header('Content-Type: application/json;charset=utf-8');
echo json_encode($data);



回答3:


verify the Content-Type meat

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


来源:https://stackoverflow.com/questions/12599258/special-characters-%c3%ab-in-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!