0

我有一个自动完成功能,用于帮助我在将行插入数据库时​​更快地添加关键字。在函数内部,我有一个变量,其中存储了所有用于建议的关键字。将一行插入数据库后,使用 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;
    }
});
4

2 回答 2

2

您不需要自己处理数据源,有一个 jQuery UI Autocomplete 选项可以满足您的需要:

看看: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" );
  }
});
于 2013-10-27T17:07:19.620 回答
0

假设从您的描述中您想要添加来自数据库的关键字

我认为最好的方法是将默认数组与来自数据库的传入值连接起来

success: function(result) {
    autocompleteKeywords = [].concat(autocompleteKeywords, result.keywords)
}
于 2013-10-27T17:13:19.920 回答