2013-07-08 83 views
0

我想知道如何限制在JavaScript文件的搜索結果,我的JS文件的詳細信息如下:限制搜索結果的Javascript

/* JS File */ 
    <script> 
    // Start Ready 
    $(document).ready(function() { 

     // Icon Click Focus 
     $('div.icon').click(function(){ 
      $('input#search').focus(); 
     }); 

     // Live Search 
     // On Search Submit and Get Results 
     function search() { 
      var query_value = $('input#search').val(); 
      $('b#search-string').html(query_value); 
      if(query_value !== ''){ 
       $.ajax({ 
        type: "POST", 
        url: "search.php", 
        data: { query: query_value }, 
        cache: false, 
        success: function(html){ 
         $("ul#results").html(html); 
        } 
       }); 
      }return false;  
     } 

     $("input#search").live("keyup", function(e) { 
      // Set Timeout 
      clearTimeout($.data(this, 'timer')); 

      // Set Search String 
      var search_string = $(this).val(); 

      // Do Search 
      if (search_string == '') { 
       $("ul#results").fadeOut(); 
       $('h4#results-text').fadeOut(); 
      }else{ 
       $("ul#results").fadeIn(); 
       $('h4#results-text').fadeIn(); 
       $(this).data('timer', setTimeout(search, 100)); 
      }; 
     }); 

    }); 
</script 

我只需要添加類似下面的代碼才能夠加載在結果之前加載圖像並將結果限制爲五個或其他內容,並且如果可能的話稍後添加加載。

<script> 
function loadSearch(query) { 
    document.body.style.overflow='hidden'; 
    if (typeof xhr != "undefined") { 
     xhr.abort(); 
     clearTimeout(timeout); 
    } 

    if (query.length >= 3) { 
     timeout = setTimeout(function() { 
      $('#moreResults').slideDown(300); 
      $('#search_results').slideDown(500).html('<br /><p align="center"><img src="http://www.tektontools.com/images/loading.gif"></p>'); 
      xhr = $.ajax({ 
       url: 'http://www.tektontools.com/search_results.inc.php?query='+encodeURIComponent(query), 
       success: function(data) { 
        $("#search_results").html(data); 
       } 
      }); 
     }, 500); 
    } else { 
     unloadSearch(); 
    } 
} 
function unloadSearch() { 
    document.body.style.overflow=''; 
    $('#search_results').delay(100).slideUp(300); 
    $('#moreResults').delay(100).slideUp(300); 
} 
</script> 

我已得到另一模板頁第2代碼,我只是沒能調整爲適合我的搜索模板(1碼),我會很感激,如果有人可以幫我調整它,非常感謝。

+0

你是說你想要一種分頁方式? – Sergio

+1

我認爲你需要在後臺代碼中進行分頁。你的PHP代碼應該支持至少有兩個基本參數'page_id'和'limit'的分頁。 –

回答

0

如果你想在javascript方面做到這一點,你可以使用slice

$.ajax({ 
    type: "POST", 
    url: "search.php", 
    data: { query: query_value }, 
    cache: false, 
    success: function(html){ 
     $("ul#results").html(html.slice(0, 5); 
    } 
}); 

我個人建議你行的在服務器端限制,儘量減少數據的你的客戶端和服務器之間傳輸量。

+0

請問,請在第一個代碼的正確位置上加上這個「分片」代碼,並將變量(「#search_results」)更改爲適合第一個代碼的代碼,非常感謝您的回覆。 – beginner

+0

@beginner我在答案的代碼部分做了很少的編輯。希望你現在可以正確地把它放到你的代碼中。 – Puuskis