Drupal中Textfield的Ajax自动完成定制
时间:2020-03-05 15:25:29 来源:igfitidea点击:
自动完成是Drupal中文本字段的一个特性。
它提供了服务器中匹配选项的下拉列表。
它是通过AJAX实现的。
要了解如何在Drupal中添加autocomplete表单元素,请访问https://www.drupal.org/node/854216
为了定制autocomplete,我们需要重写(overwriting)Drupal系统文件"misc"/自动完成.js". 理想情况下可以通过两种方式实现:
- 替换整个"自动完成.js"与定制版本
function MY_MODULE_js_alter(&$javascript) { $javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/js/autocomplete.js'; }
- "重写(overwriting)"Drupal.ACDB.prototype文件在主题中使用自定义行为脚本.js或者模块js文件,只要它添加在/misc之后/自动完成.js它将重写(overwriting)它。
/** * Performs a cached and delayed search. */ Drupal.ACDB.prototype.search = function (searchString) { var db = this; this.searchString = searchString; //See if this string needs to be searched for anyway. searchString = searchString.replace(/^\s+|\s+$/, ''); if (searchString.length <= 0 || searchString.charAt(searchString.length - 1) == ',') { return; } //See if this key has been searched for before. if (this.cache[searchString]) { return this.owner.found(this.cache[searchString]); } //Initiate delayed search. if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(function () { db.owner.setStatus('begin'); //Ajax GET request for autocompletion. We use Drupal.encodePath instead of //encodeURIComponent to allow autocomplete search terms to contain slashes. $.ajax({ type: 'GET', url: db.uri + '/' + Drupal.encodePath(searchString), dataType: 'json', success: function (matches) { if (typeof matches.status == 'undefined' || matches.status != 0) { db.cache[searchString] = matches; //Verify if these are still the matches the user wants to see. if (db.searchString == searchString) { db.owner.found(matches); } db.owner.setStatus('found'); } }, error: function (xmlhttp) { alert(Drupal.ajaxError(xmlhttp, db.uri)); } }); }, this.delay); };
现在我们逐一调整autocomplete的特性:
禁用缓存
—有时我们可能需要禁用自动完成的缓存,以使其带来更新的数据。
db.cache[searchString] = matches;
- 删除或者注释掉这一行,这将缓存搜索字符串
jQuery("#autocomplete_ElementName").result(function() { jQuery("#autocomplete_ElementName").flushCache(); });
- 刷新缓存
if (searchString.length < Min || searchString.charAt(searchString.length - 1) == ',')
强制自动完成的最小字符数
在此处用你喜欢的数值替换"Min"
this.delay = 'time_in_milliseconds';
增加/减少自动完成超时
在上面的timeout函数的任何位置添加"this.delay = 400;" (400毫秒延迟)。如果延迟值非常低,则为每个子字符串存储缓存值。例如,如果键入"abcd",则会缓存[a][ab][abc][abcd]
的结果!
dataType: 'jsonp',
解决跨域问题
将ajax数据类型从"json"更改为"jsonp"
searchString = searchString + "/" + $("#otherfield").val();