我搜索了一个术语“bi”,它应该返回一个带有初始“bi ...”的用户名。 但没有显示任何内容,没有下拉列表这是我的代码。
search.html
<html>
<div class="ui-widget">
<label for="search4">search4: </label>
<input id="search4">
</div>
<script type="text/javascript">
$(function(){
$("#search4").autocomplete({
source: '/rating/searchresult/',
minLength: 2,
});
});
</script>
</html>
url.py
url(r'^searchresult/', 'rating.views.search_images'),
views.py
def search_images(request):
if request.is_ajax():
s = request.GET.get("term", '')
search_result = UploadImage.objects.filter(user__username__icontains = s )[:20]
search = []
for result in search_result:
json_d = {}
json_d['id'] = result.id
json_d['name'] = result
json_d['value'] = result
search.append(json_d)
data = m_json.dumps(search)
else:
data = 'error'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
如果我搜索一个值,Ajax不响应并且在下拉列表中没有返回任何内容,而该术语在URl中传递
[04/Aug/2016 08:48:46] "GET /rating/searchresult/?term=bi HTTP/1.1" 200 2661
我无法理解Ajax或Django的问题在哪里 Also my content type is text html see here
答案 0 :(得分:0)
好的,从技术上来说,你做错了。
source
的{{1}}属性需要一个字符串或数据数组,您希望在输入字段中为用户提供自动完成选项。
现在您要做的就是在autocomplete
url
views.py
中的source
中简单地提供与特定视图类或方法相对应的autocomplete
实际上您需要做的是通过点击ajax
来获得url
响应,然后您将从该网址对应的类/方法获得所需的响应。
现在,您将此response
提供给autocomplete
的来源
请在此处查看source
的{{1}}如何运作 - &gt; http://api.jqueryui.com/autocomplete/#option-source
autocomplete
的官方文档 - &gt; http://api.jquery.com/jquery.ajax/
ajax
的文档 - &gt; https://api.jquery.com/jquery.get/
所以你的javascript文件看起来像这样:
$.get()
现在,如果它成功运行,那么您将在$(document).on('ready', function(){
populateSearchFieldList();
// all other code according to your needs
});
function populateSearchFieldList() {
var url = "/rating/searchresult/";
$.get(url, function(response) {
// console.log("Success..!!");
console.log(response);
// now in views.py, you've returned a list in which every
// object has an id, name and value but you
// want only the names in your autocomplete. So for that, first
// you'll have to create a list of just the names and then feed
// that list to the source of autocomplete. Like this
var searchFieldOptions = [];
var i = 0;
$.each(response,function(){
searchFieldOptions.push(response[i].name);
i++;
});
// and now make the source of autocomplete as
// searchFieldOptions like this
$(function(){
$("#search4").autocomplete({
source: searchFieldOptions,
minLength: 2,
});
});
});
}
函数中收到的response
中包含所需数据。现在,您可以将此success
用作response
的{{1}},如果它只是一个列表,或者可以进一步修改此source
并形成所需内容的autocomplete
根据您的要求。