2017-04-18 82 views
0

我试图实现一个自动完成功能的输入字段。我会使用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的,真的希望在这一个了一些指导。谢谢!

回答

0

您的要求很简单。实现这一目标的方法之一是..please按照意见

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

让我们知道

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功能可能看起来像(假设你有一个id auto-complete有5个li元素olul元素):

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