今天才开始,但是我在尝试理解JSON / AJAX等方面遇到了大量问题,我已经得到了我的代码,但我对如何将AJAX请求提取的数据返回到jQuery Auto完成功能感到困惑。
var autocomplete = new function (){
this.init = function() {
$('#insurance_destination').autocomplete({source: lookup});
}
function lookup(){
$.ajax({
url: "scripts/php/autocomplete.php",
data: {query:this.term},
dataType: "json",
cache : false,
success: function(data) {
for(key in data){
return {
label: key,
value: data[key][0]
}
}
}
});
}
}
PHP脚本返回的JSON字符串示例 {“乌干达”:[“UGA”,“UK4”,“全球不包括美国,加拿大和加勒比海”]}
答案 0 :(得分:1)
通常,您不必自己进行ajax查询:
$('#insurance_destination').autocomplete('url_here', {options_here});
这假设我们正在讨论标准的jquery自动完成插件。我能理解你吗?
修改强>
检查api
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
还有一些例子。
答案 1 :(得分:0)
这是我最终使用的代码,它适用于Chrome和Firefox,但不适用于IE 6/7 ......
var autocomplete = new function (){
this.init = function() {
$('#insurance_destination').autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "scripts/php/autocomplete.php",
dataType: "json",
data: {query:this.term},
success: function(data) {
response($.map(data.countries, function(item) {
return {
label: '<strong>'+item.name+'</strong>'+' '+item.description,
value: item.name,
code : item.region
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$('#insurance_iso_code_hidden').val(ui.item.code);
},
open: function() {
},
close: function() {
}
});
}
}