JQuery自动完成文本搜索,包含远程源的结果

时间:2017-04-18 20:11:47

标签: javascript jquery python json django

我尝试使用自动完成功能实现输入字段。我正在使用Google Books API根据用户在输入文本字段中输入的关键字自动完成图书的名称。我正在使用Django作为实现此功能的框架。

这是我迄今为止所做的:

JS

didDeselectRow

此处,$( 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。只要用户输入的关键字长度超过4,我就会向#id_book_name发送一个POST请求,该请求会映射到以下Python函数,我会点击Google Books API的端点和以特定的JSON格式返回书名:

/book-search

关键字' python'的上述函数的示例返回格式:

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)

现在,我无法弄清楚如何循环使用上面的JSON格式来显示输入文本字段下方的结果。我知道我可以使用{"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)"]} JQuery函数在append()标记内添加我的书名。但是,我仍然坚持如何循环我的响应结果以使用for循环单独获取每个书名:

<li>

我是JQuery的新手,非常感谢对此有一些指导。谢谢!

2 个答案:

答案 0 :(得分:0)

您的要求非常简单。实现这一目标的一种方法是..请遵循评论

&#13;
&#13;
$(function() {

  var myDiv = $("#mydiv"); //Assuming there is a div wrapped 
  var myUl = $('<ul/>'); //blank unordered list object

  //Your result from the query
  var result = JSON.parse('{"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)"]}');

  //Iterate through each object
  result.titles.forEach(function(item) {
    var li = $('<li/>'); //create an li item object
    li.append(item); // append the item/txt to the list item
    myUl.append(li); //append the list item to the list
  });
  myDiv.append(myUl) //Append list to the div

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='mydiv'>
  <input id='id_book_name' />
</div>
&#13;
&#13;
&#13;

告诉我们

答案 1 :(得分:0)

首先,没有理由返回一键词典。只需返回数组。所以,你的结果看起来更像是:

["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)"]

然后,将第四个参数传递给$.post,即JSON的数据类型,因此它总是自动将其解析为JavaScript数组。

$.post(url, data, onSuccess, 'json').fail(onFail);

然后你只需要一个简单的数组来追加搜索结果。

制作一个比较5个建议的数组,并且只填充前5个(因为更多可能是不必要的)。然后使用CSS隐藏空的(如#auto-complete :empty { display: none; })。您的onSuccess功能可能如下(假设您有一个olul元素,其ID为auto-complete且有li个元素):

var autoCompleteBoxes = $('#auto-complete li');

$.post(url, data, function(data) {
    for (var i = 0; i < 5; i++) {
        autoCompleteBoxes[i].text(data[i] || '');
    }
}, 'json').fail(function() {
    // Reset auto complete boxes if there was a failure.
    for (var i = 0; i < 5; i++) {
        autoCompleteBoxes[i].text('');
    }
    $('#auto-complete').hide();
}