如何在我的网站上获取国家列表

7

我正在寻找一种在下拉菜单中显示所有国家列表的方法。是否有PHP或jQuery的简短代码可以在我的网页上获取国家列表?谢谢。


1
请展示您当前的尝试,如果有的话。 - Vadim Landa
5个回答

17

最新答案。

支持Intl的浏览器现在可以以您选择的语言提供国家信息。

function getCountries(lang = 'en') {
    const A = 65
    const Z = 90
    const countryName = new Intl.DisplayNames([lang], { type: 'region' });
    const countries = {}
    for(let i=A; i<=Z; ++i) {
        for(let j=A; j<=Z; ++j) {
            let code = String.fromCharCode(i) + String.fromCharCode(j)
            let name = countryName.of(code)
            if (code !== name) {
                countries[code] = name
            }
        }
    }
    return countries
}

调用getCountries()将返回带有国家代码及其名称的对象列表,例如。
{AC: 'Ascension Island', AD: 'Andorra', AE: 'United Arab Emirates', AF: 'Afghanistan', AG: 'Antigua & Barbuda'}

2
这太棒了。为了其他查看此处的人提供上下文,该解决方案循环遍历所有可能的两个字符组合(AA,AB,AC,...),并检查 Intl 是否将其作为有效的国家代码。 - Emanuele Feliziani
如果您还想要一个将名称映射到国家代码的列表,可以执行Object.fromEntries(Object.entries(COUNTRY_CODES_TO_NAMES).map(entry => [entry[1], entry[0]])),其中COUNTRY_CODES_TO_NAMES是@Gerardlamo函数的输出。 - Emanuele Feliziani
非常感谢您,Geraldlamo。 - Rajesh Poonia
1
很遗憾,代码可能会出错,因为FF和Chrome保留了先前用过的ISO 3166-1 alpha-2代码,用于各个国家(包括南极洲、巴拿马等)。所以,如果构建一个数组的数组,你会得到重复的和多次的条目;或者如果构建一个对象,就像这个答案中一样,最后一个词法代码将获胜。这个答案对于仅仅使用名称(而不依赖于代码)或生成起始点字面字符串仍然可能有用。 - DWB

12

我使用countries-list npm包。

import countries from "countries-list";

获取有关各个国家的详细信息:

console.log(countries.countries);

会让你得到:

{
   AD: {
      name: "Andorra"
      native: "Andorra"
      phone: "376"
      continent: "EU"
      capital: "Andorra la Vella"
      currency: "EUR"
      languages: ["ca"]
      emoji: ""
      emojiU: "U+1F1E6 U+1F1E9"
   }
   ...
}

或者只是国家列表:

const countryCodes = Object.keys(countries.countries);
const countryNames = countryCodes.map(code => countries.countries[code].name);
console.log(countryNames);

将打印国家名称列表:

"Andorra"
"United Arab Emirates"
"Afghanistan"
"Antigua and Barbuda"
...

这些需要按字母顺序排序,因为它们是根据国家代码排序的:

console.log(countryNames.sort());

9

非常感谢你,Kamal。 - Rajesh Poonia
亲爱的Kamal,我需要在数据库中插入所有国家吗?因为我需要在PHP中使用它。 - Rajesh Poonia

1

Ruslan Kazakov之后。

如果你正在使用typescript和countries-list npm包,我发现以下内容可以让typescript编译器满意,如果你想要获取下拉菜单中的国家名称列表。

const countryNames = Object.values(countries.countries)
  .map((item) => item.name))
  .sort();

-4
在Struts2中,你可以获取它 - 例如,
<s:select name="name" headerKey="-1"
list="countryList" id="country" 
value="%{countryList}" 
></s:select>

在jQuery中,您需要通过ajax调用获取列表并对其进行迭代,例如:
$.ajax({
           url: 'rcmidAuditTrail.action',
           type: 'GET',
           async : false,
           dataType: 'json',
           error: function(data) {
              console.log('error');
           },
           success: function(list) {

var html = '<select>'
              $.each(list,function(i,value){
                     html+='<option>'+value+'</option>';
              });
$('dropdownId').html(html);
           }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接