隐藏Bootstrap Typeahead中的值

时间:2014-03-19 15:40:39

标签: javascript php twitter-bootstrap

我正在使用带有PHP的Bootstrap Typeahead来使用source.php显示数据库中的列表:

<?php

if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

$query = $_POST['query'];

$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();

foreach ($conn->query($sql) as $row) {
    $array[] = $row['title'] . ',' . $row['id'];
}

// Return the json array
echo json_encode($array);
}
?>

你可以看到我在数组中添加了'title'和'id'。我希望它在typeahead中显示的是标题,但我需要链接的id。这是JS:

$('#typeahead').typeahead({
source: function (query, process) {
    $.ajax({
        url: "source.php",
        type: "POST",
        data: 'query=' + query,
        dataType: 'JSON',
        async: true,
        success: function(data){
            process(data);
        }
    })
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
        updater: function (item) {
            document.location = "/companies/" + item.replace(/ /g, '-').replace(/\,/g,'/').toLowerCase() + "/";
            return item;
        }
});

在行开头document.location中,我用正斜杠替换两个值之间的逗号,它可用于例如/英格兰/ 123 /。但这是一种先行显示,将其显示为英格兰,而不仅仅是英格兰。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

确定设法获得以下结果:

PHP:     

if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

$query = $_POST['query'];

$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();

foreach ($conn->query($sql) as $row) {
    $array[] = array('label' => $row['title'], 'id' =>$row['id']);
}

// Return the json array
echo json_encode($array);
}

JS:

$('#typeahead').typeahead({
source: function (query, process) {
    $.ajax({
        url: "http://www.stubowker.com/amex/cms/source.php",
        type: "POST",
        data: 'query=' + query,
        dataType: 'JSON',
        async: true,
        success: function(data){
objects = [];
    map = {};
    $.each(data, function(i, object) {
        map[object.label] = object;
        objects.push(object.label);
    });
    process(objects);
        }
    })
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
    updater: function (item) {
        document.location = "/companies/" + map[item].label.replace(/ /g, '-').toLowerCase() + "/" + map[item].id + 

"/";
        return item;
    }
});