我正在尝试在结帐时创建城市自动完成功能,但是问题是发送的数据量太大。 因此,我只考虑在字段中键入一定数量的符号后上传数据,比如说3。
但是我不知道如何使用本机bindingHandlers来做到这一点。
这是js文件:
define([
'Magento_Ui/js/form/element/abstract',
'mage/url',
'ko',
'jquery',
'jquery/ui'
], function (Abstract, url, ko, $) {
'use strict';
ko.bindingHandlers.shippingAutoComplete = {
init: function (element, valueAccessor) {
Promise.resolve(
$.ajax({
type: 'POST',
url: url.build('ajax/url/here/'),
dataType: 'json'
})
).then(function (result_list) {
var settings = valueAccessor();
var selectedOption = settings.selected;
var options = JSON.parse(result_list);
var updateElementValueWithLabel = function (event, ui) {
// Stop the default behavior
event.preventDefault();
$(element).val(ui.item.label);
if (typeof ui.item !== "undefined") {
selectedOption(ui.item);
}
};
$(element).autocomplete({
source: options,
select: function (event, ui) {
updateElementValueWithLabel(event, ui);
}
});
});
}
};
return Abstract.extend({
selectedDepartment: ko.observable(''),
selectedCity: ko.observable(''),
postCode: ko.observable(''),
getCities: function ( request, response ) {
var departmentValue = $('[name="region"]').val();
$.ajax({
url: url.build('ajax/url/here/'),
data: JSON.stringify({
q: request.term,
filter: departmentValue
}),
contentType: "application/json",
type: "POST",
dataType: 'json',
error : function () {
alert("An error have occurred.");
},
success : function (data) {
var items = JSON.parse(data);
response(items);
}
});
}
});
});
模板:
<input class="input-text" type="text" data-bind="
shippingAutoComplete: {
selected: selectedCity,
},
event: {change: userChanges},
value: value,
valueUpdate: 'blur',
hasFocus: focused,
attr: {
name: inputName,
placeholder: placeholder,
'aria-describedby': noticeId,
id: uid
}" />
当前该代码正在运行,并且我正在按预期获得自动完成结果。但是ajax返回的结果数量太大。这就是为什么我需要输入至少3个符号后才开始上传数据。