【发布时间】:2020-07-02 22:02:23
【问题描述】:
我尝试使用 Jquery 自动完成功能在输入字段中输入国家/地区名称。相反,它绑定了所有 JSON 数据,并且搜索不会从 JSON 数据中过滤。
国家/地区的 JQUERY 自动完成功能
$("#ddlCountry").autocomplete({
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'country',
dataType: "json",
data: {
term: request.term
},
success: function(data) {
console.log(request.term)
response($.map(data, function(item, key) {
return {
label: item.country_name,
value: item.id
}
}));
},
error: function(xhr) {
console.log('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
},
minLength: 2,
select: function(event, ui) {
e.preventDefault()
},
focus: function(event, ui) {
e.preventDefault()
},
});
Views.py
def country_list(request):
if request.method == "GET":
if request.is_ajax():
obj_country_list = Country.objects.values("id", "country_name")
return HttpResponse(json.dumps(list(obj_country_list)))
JSON 数据
{"id": 1, "country_name": "Afghanistan"},
{"id": 2, "country_name": "Albania"},
{"id": 3, "country_name": "Algeria"},
{"id": 4, "country_name": "Andorra"},
{"id": 5, "country_name": "Angola"},
{"id": 6, "country_name": "Antigua and Barbuda"},
{"id": 7, "country_name": "Argentina"},
{"id": 8, "country_name": "Armenia"},
{"id": 9, "country_name": "Australia"},
{"id": 10, "country_name": "Austria"},
{"id": 11, "country_name": "Azerbaijan"},
{"id": 12, "country_name": "Bahamas"},
{"id": 13, "country_name": "Bahrain"},
{"id": 14, "country_name": "Bangladesh"},
{"id": 15, "country_name": "Barbados"},
{"id": 16, "country_name": "Belarus"},
{"id": 17, "country_name": "Belgium"},
{"id": 18, "country_name": "Belize"},
{"id": 19, "country_name": "Benin"},
{"id": 20, "country_name": "Bhutan"}]
请帮我解决一下。
【问题讨论】:
-
欢迎来到 Stack Overflow。过滤必须在您的 Python 中或在您将数据返回到
response()之前完成。 -
感谢您的建议。我尝试在 Python 中过滤并返回过滤后的数据作为响应。有效。 @Twisty
标签: python jquery django ajax jquery-ui