【问题标题】:JavaScript, jQuery, AJAX and accented characters: how to get them working?JavaScript、jQuery、AJAX 和重音字符:如何让它们工作?
【发布时间】:2013-04-12 14:32:55
【问题描述】:

我在通过 AJAX 和 jQuery 显示重音字符时遇到问题。我会更详细地解释它。

我有一个页面,其中有一个input 字段。当我用 4 个字符(必须是机场的 ICAO 代码)填充该字段时,它会通过 AJAX 调用 PHP 脚本。脚本如下:

文件: ajax.airport.php

<?php
    include("mysqlexec.inc.php");
    include("functions.inc.php");

    if(isset($_GET['icao'])){ 
        $airportData = GetAirportInfo($_GET['icao']);  

        if (!empty($airportData["Name"])) {
            echo $airportData["Name"];
        } else {
            echo "Not found!";
        }
    }
?>

函数GetAirportInfo(); 向显示机场名称的Our Airports 网站发出HTTP 请求。如果您可以查看this example page,您可能会注意到ICAO 代码是SBGL,由用户在input 上输入,返回@987654328 @ 函数(它是数组的元素)将是 Galeão - Antônio Carlos Jobim Intl,带有一些重音字符。

问题是,在文件中回显此内容时,会出现 Gale�o - Ant�nio Carlos Jobim Intl

所有文件都是UTF-8(没有BOM)。我尝试了几个函数(PHP 和 JS 类型),但都失败了。

在输入上执行的jQuery函数是这样的:

function showAirport(icao, dest) {
    var icao=icao.toUpperCase();

    if (icao.length < 4) {
       $("#"+dest).html("");
    } else {
       $("#"+dest).html('<img src="images/loadingsm.gif"/>');
       $.ajax({
           type    : "GET",
           url     : "ajax.airport.php",
           dataType: "html",
           data    : { icao: icao },
           success : function (result) {
               $("#"+dest).html(result);
           },
       });
    }
};

欢迎任何帮助。

【问题讨论】:

  • 数据库怎么样?记录编码是否正确?顺便说一句,在示例页面上,编码对我来说似乎是正确的(mac os,chrome)
  • 实际上这些数据并没有记录在任何数据库中。其目的是仅为用户交叉检查并意识到他输入了正确的国际民航组织代码而显示。 - 示例页面不是我的,它来自我们的机场网站,我从那里获取信息。我们的机场不是由我维护的:它只是从我提取数据的地方得到他们的许可。
  • 你试过mb_detect_encoding 吗?或者你可以试试 echo utf8_encode($airportData["Name"]);
  • 您是在 html 页面上打印这些吗?如果是,请检查您是否有一个指定了 charset="utf-8" 的元标记。如果 utf-8 不适合您,我也会尝试 charset="iso-8859-15"。
  • @tanaydin,utf8_decode 的使用成功了!我对该功能有错误的理解,但您引用的内容让我正确地对其进行了审查。非常感谢!

标签: php jquery ajax utf-8 non-ascii-characters


【解决方案1】:

检查 contentType 属性

function showAirport(icao, dest) {
var icao=icao.toUpperCase();

if (icao.length < 4) {
   $("#"+dest).html("");
} else {
   $("#"+dest).html('<img src="images/loadingsm.gif"/>');
   $.ajax({
       type    : "GET",
       contentType: "text/xml;charset=utf-8",
       url     : "ajax.airport.php",
       dataType: "html",
       data    : { icao: icao },
       success : function (result) {
           $("#"+dest).html(result);
       },
   });
}

};

【讨论】:

【解决方案2】:

我认为你应该在 ajax.airport.php 回显之前编码$airportData["Name"],在 ajax 回显数据之前使用json_encode()。其他一些语言需要浏览器可以识别的编码

include("mysqlexec.inc.php");
include("functions.inc.php");

if(isset($_GET['icao'])){ 
    $airportData = GetAirportInfo($_GET['icao']);  

    if (!empty($airportData["Name"])) {
        echo json_encode($airportData["Name"]);
    } else {
        echo "Not found!";
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-22
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多