dtjo51649 2015-08-08 16:22
浏览 45

在javascript中显示特殊字符

I am using the Google Places API to supply my application with a list of cities, countries, etc for a dropdown menu. I use an AJAX request to a file containing this code:

$results = file_get_contents("https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&language=EN&offset=4&key=" . $key . "&input=" . $input);
    $decode = json_decode($results, true);

    foreach($decode["predictions"] as $value){
        $json_array[] = $value["description"];
    }

    echo json_encode($json_array);

Everything seems to work okay on this side of things, however when the JSON is returned to the AJAX application, some of the characters appear incorrectly. For example, the "ã" in "São Paulo" appears as ",," or "S,,o Paulo" when I try to display the results. If I alert the result, the characters do display correctly in the pop-up - so I seem to be missing something when I give the results to the javascript to display in the drop down. (What also is irritating is that the incorrectly coded results end up getting entered into my database when the user selects from the drop down.)

I have tried encoding each string with "utf8_encode()" before I add it to "$json_array" (in the PHP file, of course), but this only seems to complicate things - it appears that the results are double-encoded or something when it is finally displayed in the javascript.

Also, I should note that the web page has the UTF-8 charset in the meta tag.

As a follow-up:

I created a simple HTML page which in which I displayed "ã" in a div, and it did show up properly. I also used jQuery to display the same character in another div on page load, and this too showed up correctly. And I didn't even need to set the encoding on that page. So I can only assume, because this test page is plain vanilla HTML, that the problem is coming from my PHP set-up.

I have added the following to the head of another PHP tests page:

mb_internal_encoding("UTF-8");
mb_http_output("UTF-8");
mb_http_input("UTF-8");
mb_language("uni");
mb_regex_encoding("UTF-8");
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=UTF-8");

but I am still seeing the characters incorrectly displayed. So to this point I have added the above, updated the default_encoding to UTF-8 in php.ini, and checked that the meta tag specifies UTF-8. This is really starting to irritate me now!

  • 写回答

3条回答 默认 最新

  • duandou2763 2015-08-08 16:30
    关注

    use one of either header:

    header('Content-type: application/json');
    header('Content-Type: text/html; charset=UTF-8);
    

    work for me in case of Arabic language.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services