我使用的是jQuery ui完整库,它通过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"
},
]
}是否可以从reply对象中判断要处理的响应,比如:
select: function(event, ui.reply) {我已经阅读了库中的api文档,但没有找到解决方案。
发布于 2018-09-02 18:35:05
source需要一个数组,所以您必须调整分配给它的内容。
在下面的示例中,我简单地创建了一个新函数来获取数据,然后访问reply数组,这就是我传递给自动完成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>
发布于 2018-09-01 10:19:42
如果使用ECMAScript 6,则可以使用对象析构:
select: function(event, { reply }) {现在,reply将是您将使用ui.reply访问的内容。
发布于 2018-09-01 11:01:31
您也可以这样使用它。
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);
}https://stackoverflow.com/questions/52126976
复制相似问题