jquery ui自动完成问题

时间:2010-05-22 20:32:06

标签: jquery jquery-ui user-interface autocomplete jquery-autocomplete

我有一个包含国家/地区的选择框,当选择一个时,我希望通过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:     [ “阿伯德尔”, “仔”, “阿伯斯威斯”, “阿宾登”, “阿克林顿”, “艾尔德里”, “奥尔德肖特”, “阿尔弗雷”, “阿洛厄”, “奥特林厄姆”, “Amersham公司”, “安多弗”,” Antrim“,”Arbroath“,”Ardrossan“,”Arnold“,”Ashford“,”Ashington“,”Ashton-under-Lyne“,”Atherton“,”Aylesbury“,”Ayr“,......]

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

有人能看出什么问题吗?

由于

2 个答案:

答案 0 :(得分: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
    });
}

答案 1 :(得分: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
      }
    )
  });
}