【问题标题】:How to auto populate preferredCountries from intl-tel-input with db output如何使用数据库输出从国际电话输入自动填充首选国家
【发布时间】:2022-04-17 22:06:04
【问题描述】:

我想用一个函数填充preferredCountries:["xx","yy","zz"],该函数从mysql db中获取最常用的国家代码,并将它们列在最前面,至少计数为4

我有一个带有 bootstrap4 和数据表的网站,并且想要填充首选列表,这样您就不必滚动太多。

var input = document.querySelector("#CountryPhone");
var iti = window.intlTelInput(input, {
    initialCountry: "auto",
    separateDialCode: "true",
    autoPlaceholder: "aggressive",
    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel- 
        input/14.0.7/js/utils.js",
    preferredCountries:["gb","us","at"],
    geoIpLookup: function(success, failure) {
        $.get("https://ipinfo.io", function() {}, 
           "jsonp").always(function(resp) {
            var countryCode = (resp && resp.country) ? resp.country : ""; 
            success(countryCode);
            });
        },
    });

我在一个单独的 php 文件中的函数中有这个 sql:

"SELECT DISTINCT c.iso_code FROM countries c
LEFT JOIN customer cu on c.country_name = cu.country_name
GROUP BY c.country_name
HAVING count(cu.country_name) >= 4
ORDER BY count(cu.country_name) DESC, c.iso_code ASC"

返回的是一个 json_encoded 输出,类似于所需的输出:["xx","yy","zz"]

我想过做这样的事情:

preferredCountries: function() {
    $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{action:"f2Countries"},
    dataType:"json",
    success:function(data){},
    error: function() {  }
 });
 },

但我在这方面并不强,所以我的猜测能力有所提高。 永远不会调用preferredCountries 下的函数。 我在它应该去的函数中启用了调试和断点,但它从来没有那么远。

所以需要一些帮助来创建正确的函数,比如我从文档中借来的 geoIpLookup 函数。

【问题讨论】:

  • Sooo.. 你有什么问题?
  • 我的想法没有奏效。 fetch.php 从未被调用,因此它可以返回数据。而且我什至不确定返回是否真的会正确填充,但是当我让函数工作时我会看到。

标签: javascript php datatables bootstrap-4 intl-tel-input


【解决方案1】:

我终于解决了我的问题。

所以基本上我想用最常用的国家代码动态填充“preferedCountries”,并按降序排列。

通过 $.ajax() 调用,我要求我的数据库按 desc 顺序获取国家代码并以 json 格式返回数据

我确保销毁 var iti 并使用该变量重新启动它。

preferedCountries = JSON.parse(data)
iti.destroy();
iti = window.intlTelInput(input, {
    separateDialCode: "true",
    autoHideDialCode: "true",
    autoPlaceholder: "polite",
    preferredCountries: preferedCountries,
    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/14.0.7/js/utils.js",
    customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
        return "e.g. " + selectedCountryPlaceholder;
    }
});

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 2020-05-18
    • 2022-01-12
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多