代码之家  ›  专栏  ›  技术社区  ›  Roger

jquery ui自动完成问题

  •  1
  • Roger  · 技术社区  · 16 年前

    我有一个包含国家的选择框,当其中一个被选中时,我希望我的城市字段的自动完成数据通过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:

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

    有人知道怎么了吗?

    2 回复  |  直到 16 年前
        1
  •  1
  •   Reto Aebersold    16 年前

    我认为您必须为异步调用使用回调方法来获取远程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
        });
    }
    
        2
  •  0
  •   Roger    16 年前

    谢谢,但答案是:

    // 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
          }
        )
      });
    }
    
    推荐文章