[英]jQuery: How to modify variable inside function
我有一個自動完成功能,用於幫助我在將行插入數據庫時更快地添加關鍵字。 在函數內部,我有一個變量,其中存儲了所有用於建議的關鍵字。 將一行插入到數據庫后,使用 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" );
}
});
假設根據您的描述,您要添加來自數據庫的關鍵字
我認為最好的方法是將默認數組與來自數據庫的傳入值連接起來
success: function(result) {
autocompleteKeywords = [].concat(autocompleteKeywords, result.keywords)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.