dtyqflrr775518 2014-12-22 05:31 采纳率: 100%
浏览 31
已采纳

Typeahead获取远程数据问题

I have some products in my database and I have used an input field for searching products. I am using Typeahead for search products with remote data. My database for products is like this

CREATE TABLE IF NOT EXISTS `products` (
  `id_product` int(10) unsigned NOT NULL,
  `name` varchar(128) NOT NULL,
  `desc` text,
  PRIMARY KEY (`id_product`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id_product`, `name`, `desc`) VALUES
(1,  'Apple', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry'),
(2,  'Box ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry'),
(2,  'Bat ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry'),
(2,  'Cat ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry'),
(2,  'Ant ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry');

And the html with js is like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script src="js/typeahead.bundle.js"></script>  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="jquery.typeahead.css">
<style>
.tt-query,
.tt-hint {
    width: 396px;
    height: 30px;
    padding: 8px 12px;
    font-size: 24px;
    line-height: 30px;
    border: 2px solid #ccc;
    -webkit-border-radius: 8px;
    -moz-border-radius: 8px;
    border-radius: 8px;
    outline: none;
}

.tt-query {
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}

.tt-hint {
    color: #999
}

.tt-dropdown-menu {
    width: 422px;
    margin-top: 12px;
    padding: 8px 0;
    background-color: #fff;
    border: 1px solid #ccc;
    border: 1px solid rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 8px;
    -moz-border-radius: 8px;
    border-radius: 8px;
    -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
    -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
    box-shadow: 0 5px 10px rgba(0,0,0,.2);
}

.tt-suggestion {
    padding: 3px 20px;
    font-size: 18px;
    line-height: 24px;
}

.tt-suggestion.tt-is-under-cursor {
    color: #fff;
    background-color: #0097cf;

}
</style>
<script type='text/javascript'>
        //<![CDATA[ 
        $(window).load(function () {
            // instantiate the bloodhound suggestion engine
            var products = new Bloodhound({
                datumTokenizer: function (d) {
                    return Bloodhound.tokenizers.whitespace(d.value);
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                remote: {
                    url: 'ajax.php?search_term=%QUERY',
                    filter: function (products) {
                        return $.map(products.results, function (product) {
                            return {
                                value: product.name
                            };
                        });
                    }
                }
            });
            // initialize the bloodhound suggestion engine
            products.initialize();
            // instantiate the typeahead UI
            $('.typeahead').typeahead(null, {
                displayKey: 'value',
                source: products.ttAdapter()
            });
        }); //]]>
    </script>   
</head>
<body>
    <input class='typeahead' placeholder='Find products...' type='text' />
</body>
</html>

In ajax.php I have used my custom query like this

$dsn = 'mysql:host=localhost; dbname=products';
$username = 'root';
$password = 'root';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
); 

$dbh = new PDO($dsn, $username, $password, $options);
$query = $_REQUEST['search_term'];
$stmt = $dbh->prepare("SELECT name from `products` WHERE `name`  LIKE '%".$query."%' ");
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();

// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
    $results[] = $row;
}
print_r($results);

// and return to typeahead
echo json_encode($results);

here its in array I am getting the products name like this

Array
(
    [0] => Bat
    [1] => Box
)

with json I am also getting the data like this

["Bat","Box"]

But I don't know why the values are not coming in the search dropdown box? Any help and suggestions will be really appreciable. Thanks

Note In console I am getting error like

Uncaught TypeError: Cannot read property 'length' of undefined

  • 写回答

1条回答 默认 最新

  • dream_life5200 2014-12-22 06:17
    关注

    Since your typehead js code is

                    filter: function (products) {
                        return $.map(products.results, function (product) {
                            return {
                                value: product.name
                            };
                        });
                    }
    

    namely products.results.name you need to format your php array so that it returns the json object properly

    // populate results
    $results = array();
    foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
    
        //add to 'results' with array with key 'name'
        $results['results'][] = array('name'=>$row);
    
    }
    
    // and return to typeahead
    echo json_encode($results);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题