1

我有一个选择框包含国家,当选择一个,我希望我的城市领域的自动填充数据通过ajax加载。jquery ui自动完成问题

这里是我的代码:

// 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公司”,“富阳”,“安特里姆”,“阿布罗斯”,“阿德罗森”,“阿诺”,“阿什福德”,“阿欣顿”,“阿什顿不足Lyne“,”Atherton“,”Aylesbury“,”Ayr“,...]

但是,它不起作用。当我开始在城市框中输入时,样式会发生变化,所以autocompleter正在做某件事,但它不会显示这些数据。如果我硬编码上述它的作品。

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

感谢

回答

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