1

嗨,我遇到了一个问题。我已经实现了 jquerys 著名的自动完成,我正在从数据库中创建一个列表(很长)以输出到自动完成字段中。但是在列表中找到正确的值需要很长时间。有谁知道我可以加快速度的方法???这是我的jQuery:

<script>
    $(function() {function log( message ) {$( "#destId" ).val( message );}
        $( "#destinations" ).autocomplete({
            source: "destinos.php",
            minLength: 2,
            select: function( event, ui ) {
                log( ui.item ?
                    "" + ui.item.id :
                    "" + this.value );}});});
    </script>

这是destinos.php:

//connect to database
include 'php/dbconn.php';
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

$qstring = "SELECT Destination as value, DestinationId as id FROM DestinationId WHERE Destination LIKE '%".$term."%'";
//query the database for entries containing the term
    $result = mysql_query($qstring);
//loop through the retrieved values   
    while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
            $row['value']=htmlentities(stripslashes($row['value']));
            $row['id']=htmlentities(stripslashes($row['id']));
            $row_set[] = $row;//build an array
    }
    echo json_encode($row_set);//format the array into json data

任何帮助将不胜感激!

4

2 回答 2

3

You most likely need to speed up your database query. You'll have to do a couple of things to do that.

  1. Make sure your Destination field has an index on it.
  2. Unless you absolutely must match from the middle of the string, drop the leading % from your LIKE query to enable the index to be used. MySQL cannot effectively use the index with the leading wildcard.
  3. If you must leave the leading % then set minLength to 3 in your jQuery. This will allow MySQL to use an optimizing algorithm on the pattern.

Source: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

于 2012-09-11T21:10:27.780 回答
1

我将开始查看数据库方面。

首先,您需要确保在Destination.

其次,您应该考虑使用LIMIT10 或 20 行。在自动完成中,在大多数情况下,您不需要一次显示那么多结果。随着用户继续快速打字,匹配计数将减少。

Third, you should use proper mysql escape on $term variable before querying with it.

The rest looks pretty straightforward.

于 2012-09-11T21:09:54.913 回答