2013-07-27 62 views
0

我想要在表單上的關鍵字有一個typeahead,我看着響應頭中的結果,他們返回整個表而不是返回縮小的結果 - 這導致它(我認爲)在返回所有結果之前超時。我使用的是阿賈克斯信息的預輸入我這兩個網站上發現:1)http://www.webmaster-source.com和2)tatiyants.com引導鍵入ajax響應沒有縮小結果

這裏是jQuery的/ JavaScript的一部分

$('#keyword').typeahead({ 
      minLength: 1, 
      source: function (query, process) { 
       items = []; 
       map = {}; 
       $.ajax({ 
        type: 'post', 
        url: 'includes/php/get_info.php', 
        data: { type: 'keyword', q: query }, 
        cache: false, 
        dataType: 'json', 
        success: function (data) { 
         $.each(data, function (i, product) { 
          map[product.keyword] = product; 
          items.push(product.keyword); 
         }); 
         return process(items); 
        } 
       }); 
      }, 
      updater: function (item) { 
       if (jQuery.type(map[item]) !== 'undefined'){ 
        //add previously used tag 
        $('#keywords').append('<div class="remove" item="'+item+'"><span class="tag">'+item+'</span><button type="button" class="close" item="'+item+'">×</button><input type="hidden" name="ci_keywords[]" value="'+item+'"></div>'); 
       } else { 
        //add the new tag 
        $('#keywords').append('<div class="remove" item="'+item+'"><span class="tag">'+item+'</span><button type="button" class="close" item="'+item+'">×</button><input type="hidden" name="ci_keywords[]" value="'+item+'"></div>'); 
       } 
      }, 
      matcher: function (item) { 
       if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) { 
        return true; 
       } 
      }, 
      sorter: function (items) { 
       items.unshift(this.query); 
       return items; 
      } 
     }); 

這裏是我的get_info.php

if(isset($_POST['type']) && $_POST['type'] == 'keyword') { 
    $keywords = $dbh->prepare("SELECT DISTINCT `keyword` FROM `ci_keywords` WHERE `keyword` LIKE ?"); 
    $keywords->execute(array('%'.$_POST['query'].'%')); 
    $results = $keywords->fetchAll(PDO::FETCH_ASSOC); 
    echo json_encode($results); 
} 

我的頁面上的HTML是:

<div class="control-group"> 
          <label class="control-label" for="keyword">Keywords or Phrases</label> 
          <div class="controls"> 
           <input class="span4" type="text" id="keyword" placeholder="Keywords" autocomplete="off"> 
           <div id="keywords" class="clearfix"></div> 
          </div> 
         </div> 

所以,我的追求離子 - 爲什麼它會返回整個列表,而不是按我發送的搜索詞進行縮小?

回答

3

您發送變量名是q

data: { type: 'keyword', q: query }, 

你在PHP中檢索變量名是query

$keywords->execute(array('%'.$_POST['query'].'%')); 

打開錯誤報告會幫助你避免這個問題。

+0

Ranty,這很尷尬!就是這樣!我很欣賞它! – doublenit

1

問題是在PHP中構建查詢。您正在將搜索字詞發送爲q,但將其作爲query訪問。所以更新$_POST['query']$_POST['q']