将动态变量传递到数组中

我想将从 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']

});


慕无忌1623718
浏览 102回答 1
1回答

红糖糍粑

在收到响应后重构代码以进行同步。var getGeoData = function (callback) {    $.ajax({      url: "https://geoip-db.com/jsonp",      jsonpCallback: "callback",      dataType: "jsonp",      success: callback    });};// Call the getGeoData function with callbackgetGeoData(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);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript