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

如何用Ajax+PHP调用Rest Countries API实现下拉框填充国家列表

解决方案:Ajax + PHP 实现国家下拉框填充

1. 后端PHP脚本(get_countries.php)

通过Curl请求Rest Countries API,提取国家名称并返回JSON格式数据:

<?php
// 初始化Curl会话
$ch = curl_init();

// 设置API请求地址,仅请求国家名称字段
curl_setopt($ch, CURLOPT_URL, 'https://restcountries.com/v3.1/all?fields=name');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// 生产环境建议开启SSL验证,开发环境可临时关闭
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// 执行请求并获取响应
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// 关闭Curl会话
curl_close($ch);

// 处理请求错误
if ($httpCode !== 200 || empty($response)) {
    http_response_code(500);
    echo json_encode(['error' => '无法获取国家数据']);
    exit;
}

// 解析JSON响应,提取常用国家名称并排序
$countries = json_decode($response, true);
$countryList = [];
foreach ($countries as $country) {
    $countryList[] = $country['name']['common'];
}
sort($countryList);

// 返回JSON格式的国家列表
header('Content-Type: application/json');
echo json_encode($countryList);
?>

2. 前端Ajax实现(原生JavaScript)

通过XMLHttpRequest调用PHP接口,动态填充下拉框:

<!-- HTML下拉框 -->
<select id="countrySelect"></select>

<script>
const countrySelect = document.getElementById('countrySelect');

// 创建Ajax请求
const xhr = new XMLHttpRequest();
xhr.open('GET', 'get_countries.php', true);

xhr.onload = function() {
    if (this.status === 200) {
        try {
            const countries = JSON.parse(this.responseText);
            // 清空原有选项并添加默认提示
            countrySelect.innerHTML = '<option value="">请选择国家</option>';
            // 遍历生成国家选项
            countries.forEach(country => {
                const option = document.createElement('option');
                option.textContent = country;
                option.value = country;
                countrySelect.appendChild(option);
            });
        } catch (e) {
            console.error('数据解析失败:', e);
        }
    } else {
        console.error('请求失败,状态码:', this.status);
    }
};

xhr.onerror = function() {
    console.error('网络请求错误');
};

// 发送请求
xhr.send();
</script>

3. 可选:jQuery版本Ajax实现

如果项目中已引入jQuery,可使用更简洁的写法:

<select id="countrySelect"></select>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $.ajax({
        url: 'get_countries.php',
        type: 'GET',
        dataType: 'json',
        success: function(countries) {
            $('#countrySelect')
                .empty()
                .append('<option value="">请选择国家</option>')
                .append(countries.map(country => `<option value="${country}">${country}</option>`).join(''));
        },
        error: function(xhr, status, error) {
            console.error('请求失败:', error);
        }
    });
});
</script>

注意事项

  • 生产环境请开启CURLOPT_SSL_VERIFYPEER,并配置合法的CA证书路径,保障请求安全
  • 可根据需求修改Rest Countries API的请求参数,比如添加fields=name,cca2获取国家代码
  • 可添加加载动画或提示文本,提升用户等待体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:45:27