1

i've got a select box containing countries, and when one is selected, i want my autocomplete data for the city field to load via ajax.

这是我的代码:

// Sets up the autocompleter depending on the currently
// selected country
$(document).ready(function() {
  var cache = getCities();
  $('#registration_city_id').autocomplete(
    {
      source: cache               
    }
  );

  cache = getCities();

  // update the cache array when a different country is selected
  $("#registration_country_id").change(function() {
    cache = getCities();
  });
});

/**
 * Gets the cities associated with the currently selected country
 */
function getCities()
{
  var cityId = $("#registration_country_id :selected").attr('value');
  return $.getJSON("/ajax/cities/" + cityId + ".html");
}

这将返回以下 json: ["Aberdare","Aberdeen","Aberystwyth","Abingdon","Accrington","Airdrie","Aldershot","Alfreton","Alloa","Altrincham","Amersham" “安多弗”、“安特里姆”、“阿布罗斯”、“阿德罗桑”、“阿诺德”、“阿什福德”、“阿什顿”、“阿什顿安德莱恩”、“阿瑟顿”、“艾尔斯伯里”、“艾尔”。 ..]

但是,它不起作用。当我开始在城市框中输入时,样式会发生变化,因此自动完成器正在执行某些操作,但不会显示此数据。如果我对上面的内容进行硬编码,它可以工作。

任何人都可以看到有什么问题吗?

谢谢

4

2 回答 2

1

我认为您必须为异步调用使用回调方法来获取远程 JSON 数据(请参阅Ajax/jQuery.getJSON)。也许您可以将城市存储在全局变量中或将响应直接设置为自动完成控件的来源:

function updateCities()
{
    var cityId = $("#registration_country_id :selected").attr('value');
    $.getJSON("/ajax/cities/" + cityId + ".html", function(json){
       CITY_CACHE = json;
       //Alternatively set the source of the autocomplete control
    });
}
于 2010-05-22T21:28:36.020 回答
0

谢谢,但答案是:

// Sets up the autocompleter depending on the currently
// selected country
$(document).ready(function() {

  setupAutocompleter();

  // update the cache array when a different country is selected
  $("#registration_country_id").change(function() {
    setupAutocompleter();
  });
});

function setupAutocompleter()
{
  var cityId = $("#registration_country_id :selected").attr('value');
  $.getJSON("/ajax/cities/" + cityId + ".html", function(cities) {
    $('#registration_city_id').autocomplete(
      {
        source: cities
      }
    )
  });
}
于 2010-05-23T09:01:50.800 回答