【问题标题】:JQuery autocomplete text search with results from remote source带有远程源结果的 JQuery 自动完成文本搜索
【发布时间】: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


    【解决方案1】:

    您的要求很简单。实现这一目标的一种方法是..请关注 cmets

    $(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
    
    })
    <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>

    让我们知道

    【讨论】:

      【解决方案2】:

      首先,没有理由返回一键字典。只需返回数组。因此,您的结果看起来更像:

      ["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 有 5 个 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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-19
        • 2012-12-12
        • 2014-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        相关资源
        最近更新 更多