下面是我处理 Ajax/jQuery 请求的 Django 代码。带有“q”参数的 Django 过滤器方法不起作用。这可能是因为 Ajax 请求是 JSON 格式。有人可以建议我哪里出错了吗?
视图.py
def get_names(request):
q = request.GET.get('term', '')
names = Names.objects.filter(names__startswith=q)[:10]
results = []
if names.count > 0:
for name in names:
name_json = {}
name_json['id'] = name.id
name_json['label'] = name.name
name_json['value'] = name.name
results.append(name_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
下面是我的 jQuery 代码
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "/get_names/",
dataType: "json",
crossDomain: true,
data: {
term: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});});