jquery ui 自动完成问题
我有一个包含国家/地区的选择框,当选择一个国家/地区时,我希望通过 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: [“阿伯德尔”、“阿伯丁”、“阿伯里斯特威斯”、“阿宾登”、“阿克灵顿”、“艾尔德里”、“奥尔德肖特”、“阿尔弗里顿”、“阿洛”、“奥特灵厄姆”、“阿默舍姆”、“安多佛”、”安特里姆”、“阿布罗斯”、“阿德罗森”、“阿诺德”、“阿什福德”、“阿什顿”、“阿什顿安德莱恩”、“阿瑟顿”、“艾尔斯伯里”、“艾尔”,...]
但是,它不起作用。当我开始在城市框中输入内容时,样式会发生变化,因此自动完成器正在执行某些操作,但它不会显示此数据。如果我对上面的内容进行硬编码,它就可以工作。
谁能看出出了什么问题吗?
谢谢
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.
here's my code:
// 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");
}
This returns the following 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",... ]
But, it doesn't work. When i start typing in the city box, the style changes so the autocompleter is doing something, but it won't display this data. If i hard-code the above it works.
Can anyone see what's wrong?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您必须使用异步调用的回调方法来获取远程 JSON 数据(请参阅 Ajax/jQuery.getJSON )。也许您可以将城市存储在全局变量中或直接将响应设置为自动完成控件的源:
I think you have to use a callback method for your asynchronous call to get the remote JSON data (See Ajax/jQuery.getJSON). Maybe you can store the cities in a global variable or set the response directly as source of your autocomplete control:
谢谢,但答案是:
Thanks, but the answer was: