簡體   English   中英

在Bootstrap Typeahead中隱藏值

[英]Hide value in Bootstrap Typeahead

我將Bootstrap Typeahead與PHP結合使用,以使用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”。 我希望它在預輸入中顯示的只是標題,但我需要鏈接的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開頭的行中,我用正斜杠替換了兩個值之間的逗號,例如/ england / 123 /。 但這是預先輸入的顯示,顯示為英格蘭123,而不僅僅是英格蘭。

任何幫助將不勝感激。

OK設法獲得了以下結果:

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;
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM