【问题标题】:jquery ui autocomplete problemjquery ui自动完成问题
【发布时间】:2010-05-22 20:32:06
【问题描述】:

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","Andover"," Antrim","Arbroath","Ardrossan","Arnold","Ashford","Ashington","Ashton-under-Lyne","Atherton","Aylesbury","Ayr",...]

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

谁能看出问题所在?

谢谢

【问题讨论】:

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


    【解决方案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
        });
    }
    

    【讨论】:

      【解决方案2】:

      谢谢,但答案是:

      // 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
            }
          )
        });
      }
      

      【讨论】:

        猜你喜欢
        • 2011-11-16
        • 2017-06-19
        • 2011-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多