问题
In my script to autocomplete I set a json file:
SCRIPT
<script type="text/javascript">
$("#tags").autocomplete({
source: function(request, response) {
$.ajax({
url: "test.json",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item.name_test };
}));
}
});
}
});
</script>
HTML
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
The JSON file
[{
"id_test": "7",
"name_test": "Tejido",
"price": "65"
}, {
"id_test": "8",
"name_test": "Semen",
"price": "120"
}, {
"id_test": "6",
"name_test": "Saliva",
"price": "20"
}, {
"id_test": "2",
"name_test": "Analisis urinario",
"price": "150"
}, {
"id_test": "3",
"name_test": "Analisis sanguineo",
"price": "1502"
}, {
"id_test": "4",
"name_test": "Analisis fecal",
"price": "20"
}]
But when I type a name into the input, all the elements are listed.
What is my error?
回答1:
When you use a remote source, as your code is using, you must need to filter the results in the server side or in the success
callback from the ajax call. In your case you can use something like:
...
success: function (data) {
var tag_val = $("#tags").val();
response($.map(data, function (item) {
//filtering results....
if (item.name_test.indexOf(tag_val) != -1) {
return {
label: item.name_test
};
}
}));
}
来源:https://stackoverflow.com/questions/26936380/jquery-autocomplete-from-json-list-all-elements