2017-04-18 85 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(); 
}