我试图实现一个自动完成功能的输入字段。我会使用Google图书API根据用户在输入文本字段中输入的关键字自动完成图书的名称。我将使用Django作为我的框架来实现此功能。JQuery自动完成文本搜索与远程源的结果
这是我已经能够到目前为止做:
JS
$(document).ready(function()
{
$("#id_book_name").on("change paste keyup", function()
{
var app_url = document.location.origin;
var book_name = $('#id_book_name').val();
var url = app_url+'/book-search/';
if(book_name.length > 4)
{
var data = {
'book_name': book_name,
'csrfmiddlewaretoken': document.getElementsByName('csrfmiddlewaretoken')[0].value,
};
console.log(data);
$.post(url, data).done(function(result)
{
for(var book_title of result)
{
console.log(book_title);
}
console.log(result);
}).fail(function(error)
{
console.log(error)
});
return false;
}
});
});
这里,#id_book_name
是我输入文本字段的ID。只要用户输入的关键字长度超过4,我就会发送一个POST请求到/book-search
,该请求被映射到以下Python函数,我打到Google Books API的端点并返回特定JSON格式的书名:关键字“蟒蛇”上述功能的
def book_search(request):
book_results = {'titles':[]}
key = 'XXXXXXX'
url = 'https://www.googleapis.com/books/v1/volumes?q=' + request.POST['book_name'] + '&maxResults=5&key=' + key
result = requests.get(url)
json_result = json.loads(result.text)
if 'items' in json_result:
for e in json_result['items']:
if 'industryIdentifiers' in e['volumeInfo']:
isbn = ''
for identifier in e['volumeInfo']['industryIdentifiers']:
isbn = identifier['identifier'] if (identifier['type'] == 'ISBN_10') else isbn
if 'subtitle' in e['volumeInfo']:
book_results['titles'].append(e['volumeInfo']['title'] + ' - '
+ e['volumeInfo']['subtitle'] + ' (' + isbn + ')')
else:
book_results['titles'].append(e['volumeInfo']['title'] + ' (' + isbn + ')')
result = json.dumps(book_results)
return HttpResponse(result)
采样返回格式:
{"titles": ["Python - A Study of Delphic Myth and Its Origins (0520040910)", "Python Machine Learning (1783555149)", "Learn Python the Hard Way - A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code (0133124347)", "Natural Language Processing with Python - Analyzing Text with the Natural Language Toolkit (0596555717)", "Python (0201748843)"]}
现在,我无法弄清楚是如何循环通过上面的JSON格式显示结果在我的输入文本字段下面。我知道我可以使用append()
JQuery函数在<li>
标记中添加我的书名。但是,我坚持就如何遍历我的反应结果分别获得使用一个for循环每本书的书名:
for(var book_title of result)
{
console.log(book_title);
}
我新的jQuery的,真的希望在这一个了一些指导。谢谢!