【发布时间】:2017-04-18 20:11:46
【问题描述】:
我正在尝试实现一个具有自动完成功能的输入字段。我将使用 Google Books API 根据用户在输入文本字段中输入的关键字自动完成书名。我将使用 Django 作为我的框架来实现这个功能。
这是我目前能够做到的:
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,我就会向 /book-search 发送一个 POST 请求,该请求映射到以下 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)
上述函数对于关键字'python'的示例返回格式:
{"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 的新手,非常感谢有关这方面的一些指导。谢谢!
【问题讨论】:
标签: javascript jquery python json django