<input aria-label="Text input with dropdown button" class="form-control" type="search">
// jQuery UI autocomplete 动态提示搜索建议
$('section div input[type="search"]').autocomplete({
// 触发该事件的最短字符数
minLength: 0,
'source'(request, response) {
// 如果变量 xhr 在全局范围内使用,它会在 makeRequest() 函数中被相互覆盖,从而导致资源竞争。
// 为了避免这个情况,请在包含 AJAX 函数的闭包中声明 xhr 变量。
let xhr
// Old compatibility code, no longer needed.
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) { // IE 6 and older
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.open('POST', '/findRecordNamesBy?searchGroupBy=' + findSelect.value + '&recordName=' + request.term)
// 这似乎是默认设置?
// 如果不设置响应头 Cache-Control: no-cache 浏览器将会把响应缓存下来而且再也无法重新提交请求。
// 你也可以添加一个总是不同的 GET 参数,比如时间戳或者随机数
xhr.setRequestHeader('Cache-Control', 'no-cache')
// 因为开启了 csrf,所以增加请求头
xhr.setRequestHeader('X-CSRF-Token', token)
// 请求响应格式
xhr.responseType = 'json'
xhr.send()
// callback
xhr.onreadystatechange = function () {
console.log(xhr);
console.log(xhr.readyState);
console.log(xhr.status);
console.log(xhr.response);
// 前面设置了 xhr.responseType = 'json'
// xhr.responseText 会报错
// console.log(xhr.responseText);
console.log(xhr.responseURL);
console.log(xhr.getAllResponseHeaders());
// 在通信错误的事件中(例如服务器宕机),在访问响应状态 onreadystatechange 方法中会抛出一个例外。
// 为了缓和这种情况,则可以使用 try...catch 把 if...then 语句包裹起来。
try {
if (XMLHttpRequest.DONE === xhr.readyState) {
if (200 === xhr.status) {
response(xhr.response);
/*$('#ui-id-2').prepend('<div class="delete-record-nane" style="background-color: #ff3300">test-before</div>')
.append('<div class="delete-record-nane" style="background-color: #ff3300">test-after</div>')*/
} else {
$('section div input[type="search"]').autocomplete('close')
}
}
} catch (e) {
console.log('Caught Exception: ' + e.description);
}
}
},
'select'(event, ui) {
// 以下两个属性都可以正确获取值
// ui.item.label
// ui.item.value
this.value = ui.item.value
this.blur()
reset()
ajaxRequestBy(0, '', '')
// 如果不 return,jQuery UI 会继续执行自己的 select 方法
return false
}
}).focus(function () {
// 该函数作用:第一次点击输入框就触发该事件
$(this).autocomplete('search', this.value)
});