You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DataTables国家列中添加国旗与完整国家名称

实现DataTables国家列显示国旗、完整名称与代码

步骤1:准备国旗资源

  • 图标文件方式:在项目中创建images/flags/目录,放入对应国家的图标(文件名用小写国家代码,比如ca.png、us.png、de.png、gb.png)。
  • CSS类方式:定义CSS类通过背景图显示国旗:
    .flag { display: inline-block; width: 20px; height: 15px; margin-right: 8px; background-size: cover; }
    .flag-ca { background-image: url('images/flags/ca.png'); }
    .flag-us { background-image: url('images/flags/us.png'); }
    /* 按需添加其他国家对应的类 */
    

步骤2:修改PHP后端(j-t.php)

更新代码添加国家映射、生成带国旗的HTML内容,同时完善搜索过滤逻辑(防范SQL注入):

<?php
// 假设$conn是已建立的数据库连接
$requestData = $_REQUEST;
$searchValue = isset($requestData['search']['value']) ? $requestData['search']['value'] : '';

// 国家代码与完整名称的映射表
$countryMap = [
    'CA' => 'Canada',
    'US' => 'United States',
    'DE' => 'Germany',
    'GB' => 'United Kingdom'
    // 可按需扩展更多国家
];

// 基础SQL语句
$sql = "SELECT * FROM info WHERE type='1' AND sold='0'";
$whereConditions = [];

// 全局搜索处理
if (!empty($searchValue)) {
    $escapedSearch = mysqli_real_escape_string($conn, $searchValue);
    $whereConditions[] = "(
        types LIKE '%{$escapedSearch}%' 
        OR country LIKE '%{$escapedSearch}%' 
        OR infos LIKE '%{$escapedSearch}%' 
        OR price LIKE '%{$escapedSearch}%' 
        OR email LIKE '%{$escapedSearch}%'
    )";
}

// 列搜索处理
$columns = ['types', 'country', 'infos', 'price', 'email'];
for ($i = 0; $i < count($columns); $i++) {
    $colSearch = isset($requestData['columns'][$i]['search']['value']) ? $requestData['columns'][$i]['search']['value'] : '';
    if (!empty($colSearch)) {
        $escapedColSearch = mysqli_real_escape_string($conn, $colSearch);
        $whereConditions[] = "{$columns[$i]} LIKE '%{$escapedColSearch}%'";
    }
}

// 拼接过滤条件
if (!empty($whereConditions)) {
    $sql .= " AND " . implode(' AND ', $whereConditions);
}

// 执行查询并统计数据
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$totalData = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM info WHERE type='1' AND sold='0'"));
$totalFiltered = mysqli_num_rows($query);

// 组装返回数据
$data = [];
while ($row = mysqli_fetch_array($query)) {
    $nestedData = [];
    $nestedData[] = $row["types"];
    
    // 生成国家列的HTML内容
    $countryCode = $row["country"];
    $countryName = isset($countryMap[$countryCode]) ? $countryMap[$countryCode] : $countryCode;
    
    // 图标文件方式的HTML
    $countryHtml = "<img src='images/flags/" . strtolower($countryCode) . ".png' alt='{$countryName}' style='width:20px; margin-right:8px;'>{$countryName} ({$countryCode})";
    
    // CSS类方式的HTML(替换上面的行)
    // $countryHtml = "<span class='flag flag-" . strtolower($countryCode) . "'></span>{$countryName} ({$countryCode})";
    
    $nestedData[] = $countryHtml;
    $nestedData[] = $row["infos"];
    $nestedData[] = $row["price"];
    $nestedData[] = $row["email"];
    
    $data[] = $nestedData;
}

// 返回JSON格式数据
$json_data = [
    "draw"            => intval($requestData['draw']),
    "recordsTotal"    => intval($totalData),
    "recordsFiltered" => intval($totalFiltered),
    "data"            => $data
];

echo json_encode($json_data);
?>

步骤3:更新DataTables前端配置

确保国家列能正确渲染HTML内容,修改JavaScript代码:

$(document).ready(function() {
    var dataTable = $("#example").DataTable({
        processing: true,
        bSort: false,
        serverSide: true,
        iDisplayLength: 10,
        ajax: {
            url: "json/j-t.php",
            type: "POST"
        },
        columnDefs: [
            {
                targets: 1, // 国家列的索引(从0开始,types为第0列,country为第1列)
                render: function(data, type, row) {
                    return data; // 直接返回HTML内容,允许页面渲染
                }
            }
        ]
    });

    $("#example_filter").css("display","none"); // 隐藏全局搜索框
    
    $(".example-search-input").on("keyup click change", function () {
        var ixoh = $(this).attr("id");
        var vxoh = $(this).val();
        dataTable.columns(ixoh).search(vxoh).draw();
    });
});

补充说明

  • 搜索匹配:当前配置支持按国家代码搜索,若需支持按完整国家名称搜索,可在PHP的全局搜索逻辑中添加对映射名称的判断,或直接在数据库中新增国家名称字段(更高效)。
  • 样式调整:可根据需求修改国旗图标尺寸、间距等样式参数。

内容的提问来源于stack exchange,提问作者ana williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:40:24