2014-05-02 34 views
0

出於某種原因,我無法獲得用第一個字母進行過濾的文本框,而不是將所有單詞都包含在特定字母中。
以下是我想它的工作的例子:http://jsfiddle.net/miroslav/yLdn3/jQuery自動完成:按首字母過濾

這裏是我的代碼(一切正常,它就會從數據庫表中的地址,但如果我插入「一個」它會給我所有的地址包含「a」,但我想要以「a」開頭的那些)。

getautocomplete.php

<?php 
mysql_connect("localhost","username","password"); 
mysql_select_db("databasename"); 

$term=$_GET["term"]; 

$query=mysql_query("SELECT * FROM table where address like '%".$term."%'"); 
$json=array(); 

    while($table=mysql_fetch_array($query)){ 
     $json[]=array(
        'value'=> $table["address"], 
        'label'=>$table["address"] 
         ); 
    } 

echo json_encode($json); 

?> 

autocomplete.php

<html> 
    <head> 
     <script type="text/javascript" 
     src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
     <script type="text/javascript" 
     src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script> 
     <link rel="stylesheet" type="text/css" 
     href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" /> 

     <script type="text/javascript"> 
       $(document).ready(function(){ 
         $("#address").autocomplete({ 
           source:'getautocomplete.php', 
         }); 

     // Overrides the default autocomplete filter function to search only from the beginning of the string 
     $.ui.autocomplete.filter = function (array, term) { 
       var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i"); 
       return $.grep(array, function (value) { 
         return matcher.test(value.label || value.value || value); 
       }); 
       }; 
     })(); 
     </script> 
    </head> 

    <body> 

     <form method="post" action=""> 
      Name : <input type="text" id="address" name="address" /> 
     </form> 

    </body> 
<html> 
+1

我建議改變你的SQL查詢來返回你想要的,而不是過濾客戶端的數據。 –

回答

1

在數據庫中查詢術語之前刪除%。它在正則表達式中的工作方式與.*類似,因此您可以使用類似.*term.*的內容。

+0

嗯..由於某種原因,這打破了整個事情的分離和自動完成不會給我任何建議(刪除之前的術語「%」):$ query = mysql_query(「SELECT * FROM table where address like'」。$ term 。 「%'」); – user3596479

0

documentation它說:

字符串:當使用字符串,則自動完成插件預計 字符串以指向URL資源,將返回JSON數據。 [...] 自動填充插件不會過濾搜索結果,而是在查詢 字符串中添加術語字段,服務器端腳本應使用 來過濾結果。

您使用的代碼不是必需的。調整服務器端代碼以返回所需的結果。解決辦法是在where子句中使用LIKE '<term>%'

0

嘗試使用此查詢:

SELECT * FROM table where substr(address,1,1) like '%".$term."%'"