我正在使用jQuery ui-complete库,它通过get请求调用端点来填充建议的autors列表:
$("#author-name").autocomplete({
source: "/authors/get.json",
minLength: 5,
select: function(event, ui) {
event.preventDefault();
$("#author-name").val(ui.item.label);
$("#author-id").val(ui.item.value);
}
});
问题是回复的格式,它包含在索引数组中,如下所示:
{
"reply": [
{
"value": 9,
"label": "Joe Bloggs"
},
]
}
是否可以通过回复对象告诉响应,例如:
select: function(event, ui.reply) {
我已经阅读了库中的api文档,但找不到解决方案。
source
期待一个阵列,所以你将不得不调整你分配给它的东西。
在下面的例子中,我只是创建了一个新函数来获取数据然后访问reply
数组,这就是我传递给Autocomplete source
的内容
$(document).ready(function() {
function getResponse() {
var response = {
"reply": [{
"value": 9,
"label": "Joe Bloggs"
},
{
"value": 10,
"label": "foo"
},
]
}; // in your case: read data from /authors/get.json
return response.reply;
}
$("#tags").autocomplete({
source: getResponse(),
select: function(event, ui) {
event.preventDefault();
console.log(ui.item.value);
console.log(ui.item.label);
}
});
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
如果使用ECMAScript 6,则可以使用对象解构:
select: function(event, { reply }) {
reply
现在将是你用ui.reply
访问的其他内容。
你也可以这样使用它
select: function(event, ui) {
event.preventDefault();
var reply = ui.reply;
//And Because it is an array you should use index on it.
$("#author-name").val(reply[0].label);
$("#author-id").val(reply[0].value);
}