JQuery autocomplete结合ajax实战

Published: 2013-12-21 Category: jquery Tags:

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

<title>jQuery Autocomplete Plugin</title>
<script type="text/javascript" src="../jquery_autocomplete/lib/jquery.js"></script>
<script type='text/javascript' src='../jquery_autocomplete/lib/jquery.bgiframe.min.js'></script>
<script type='text/javascript' src='../jquery_autocomplete/lib/jquery.ajaxQueue.js'></script>
<script type='text/javascript' src='../jquery_autocomplete/jquery.autocomplete.js'></script>
<script type='text/javascript' src='../jquery_autocomplete/lib/thickbox-compressed.js'></script>
<link rel="stylesheet" type="text/css" href="../jquery_autocomplete/jquery.autocomplete.css" />

$().ready(function() {
   
    $("#suggest1").autocomplete("ajax.php", {
        minChars: 0,
        width: 230,
        highlight: false,
        scrollHeight: 300,
        matchContains: "word",   
        autoFill: false,   
        parse: function(data) {
            return $.map(eval(data), function(row) {
                return {
                    data: row,
                    value: row.name,
                    result: row.to
                }
            }); 
        },
        formatItem: function(row, i, max) {
          return i + '/' + max + ':"' + row.name + '"[' + row.to + ']';
          },
        formatMatch: function(row, i, max) {
         return row.name + row.to;
        },
         formatResult: function(row) {
          return row.to;
        }
    }).result(function(event, row, formatted) {
                    return row.to;
             });
    

});

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>

<h1 id="banner">DEMO</h1>

<div id="content">
    
    <form>
        <p>
            <label>测试:</label>
            <input type="text" id="suggest1" size="30px"/>
            
        </p>
        
    </form>
</div>

</body>
</html>

以下是后端处理

ajax.php

<?php

$conn = @mysql_connect("localhost","root","") or die("Failed!");
mysql_select_db("jquery_test",$conn);
mysql_query("set names 'utf8'");

$q = $_GET["q"];
if (!$q) return;

$items = array();
$sql1 = mysql_query("select `CLIENT_N_SHORT`,`CLIENT_NAME` from `client`");
while($row = mysql_fetch_array($sql1)){
    $key = $row['CLIENT_N_SHORT'];
    $value = $row['CLIENT_NAME'];
    
    if (strpos($value, $q) !== false) {
        array_push($items, array(
            "name" => urlencode($key),
            "to" => urlencode($value)
        ));

    
    }
}
//print_r($items);
//exit();
//echo "<hr>";

echo urldecode( json_encode($items) );
?>

转载请注明:¦http://www.jia58960.me

Fork me on GitHub