我想将我从AJAX调用中获得的值添加到我提供给countrySelect()
的数组中;
我希望以下示例中的cc
变量在此数组中传递:
preferredCountries: ['pk','gb', 'us']
我尝试过此方法,但对我不起作用。
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
var cc = location.country_code;
var ncc = cc.toLowerCase();
}
});
$("#country_selector").countrySelect({
preferredCountries: ['pk', 'gb', 'us']
});
答案 0 :(得分:0)
获得响应后,重构代码以进行同步。
var getGeoData = function (callback) {
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: callback
});
};
// Call the getGeoData function with callback
getGeoData(function (location) {
var cc = location.country_code;
var ncc = cc.toLowerCase();
sessionStorage.setItem('lastname', ncc);
$('#country_selector').attr('selected', true);
const countrySelectConfig = {
preferredCountries: ['pk', 'gb', 'us']
};
countrySelectConfig.preferredCountries.push(cc);
$("#country_selector").countrySelect(countrySelectConfig);
});