我有一个自动完成功能,可以帮助我在将行插入数据库时更快地添加关键字。在函数内部,我有一个变量,其中存储了用于建议的所有关键字。将一行插入数据库后,使用 AJAX,我从数据库中获取所有关键字,包括我刚刚添加的行中的关键字。
问题是我想通过添加我刚刚使用 AJAX 从数据库获取的关键字来修改存储旧关键字的变量。
这是代码:
var autocompleteKeywords = [ 'keyword 1', 'keyword 2', 'keyword 3' ];
// Autocomplete tags
$('#search_keyword').autocomplete({
maxHeight: 400,
width: 200,
lookup: autocompleteKeywords
});
我想用 AJAX 获得的新关键字修改的变量是 autocompleteKeywords
。
这是 AJAX:
$.ajax({
url: "ajax_actions.php",
type: "GET",
data: { action: "select_keywords" },
dataType: "json",
async: false,
success: function(result)
{
autocompleteKeywords = result.keywords;
}
});
最佳答案
您不需要自己处理数据源,有一个 jQuery UI 自动完成选项可以满足您的需求:
看看:http://jqueryui.com/autocomplete/#remote
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
或这里:http://jqueryui.com/autocomplete/#remote-jsonp
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
关于javascript - jQuery:如何修改函数内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620729/